OnClickListener() implementation of Array Of Buttons in Android
I am writing an Android Application which outputs some array of buttons dynamically. My question is how to implement onClickListener() functionality for Arra开发者_如何转开发y Of Buttons. I mean how to recognize the button that is clicked in public void onClick() method ? I need to display a toast based on the button that is clicked.
The onClick() method is passed the View that was clicked...
public void onClick(View v) {
...
}
Use v.getId() to return the button's identifier.
you could create a class derived from OnClickListener
, that, in the constructor, takes the button ID.
Something like:
class MyClickListener extends OnClickListener() {
int buttonId;
MyClickListener(int id) {
buttonId = id;
}
protected void onClick(View v) {
... // do something with buttonId
}
}
Then, in your onCreate
, you would do:
int i, nb = mButtons.size(); // if mButtons is a List<Button>
for (i = 0; i < nb; i++) {
mButtons.get(i).setOnClickListener(new MyClickListener(i));
}
精彩评论