android中的OnClickListener两种实现方式

android的activity点击事件中,通过OnClickListener来实现,要实现点击事件有两种方式

1、通过定义一个OnClickListener的内部类来实现

The example below shows how to register an on-click listener for a Button.
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked
    }
};

protected void onCreate(Bundle savedValues) {
    ...
    // Capture our button from layout
    Button button = (Button)findViewById(R.id.corky);
    // Register the onClick listener with the implementation above
    button.setOnClickListener(mCorkyListener);
    ...
}

  

2、通过实现View.OnClickListener接口来实现

public class ExampleActivity extends Activity implements OnClickListener {
    protected void onCreate(Bundle savedValues) {
        ...
         Button button = (Button)findViewById(R.id.corky);
        button.setOnClickListener(this);
    }

    // Implement the OnClickListener callback
    public void onClick(View v) {
      // do something when the button is clicked
    }
}

  

原文地址:https://www.cnblogs.com/mxm2005/p/4800130.html