My understanding is that when I'm creating a button object that listens for a click, I have to:
- Create the button object
- Use
OnClickListner
to make it listen to the user's click
- Use
onClick
to execute actions after the user clicks the button
Now,
- Where does
setOnClickListener
fit into the above logic?
- Which one actually listens to the button click?
setOnClickListener
?
OnClickListener
?
View.OnClickListener
?
- What are the differences between those three?
Here is what I found in Android Dev:
//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);
...
}
You may also find it more convenient to implement OnClickListener
as a part of your Activity
. This will avoid the extra class load and object allocations. For example:
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
}
}
question from:
https://stackoverflow.com/questions/29479647/android-setonclicklistener-vs-onclicklistener-vs-view-onclicklistener 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…