Getting id of programmatically generated grid of buttons in Android
I have a similar query to the one posted here. I create a grid consisting of a variable number of buttons, at runtime (in a TableLayout), and would like to find the index of the button pressed. The actual Button objects are currently stored in an array, although I'm not sure if that is really necessary. I tried to write the ClickListener using something along the lines of:
public void onClick(View view) {
开发者_运维技巧 Button clickedButton = (Button) view;
int buttonID = clickedButton.getId();
but this just always returns -1. Is it possible to get the id (or some other reference to the button pressed) without predefining the buttons in xml?
The solution in the other post describes cycling through the whole array of Buttons and comparing ids. Is there a more elegant way to do this?
You can manually set an ID for dynamically created widgets by this method.
You don't need ids given that you have references.
final Button b1 = new Button(this);
final Button b2 = new Button(this);
final Button b3 = new Button(this);
Button[] buttons = new Button[] { b1, b2, b3 };
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
if (v == b1) {
// TODO
} else if (v == b2) {
// TODO
} else if (v == b3) {
// TODO
}
}
};
for (Button b : buttons) {
b.setOnClickListener(listener);
}
In case anyone needs this, this is what I prefer to do. A listener is a class too, so you can create instance variables for it.
new Listener(id) {
private int id;
public Listener(int id) {
this.id = id;
}
private void onClick(View view) {
buttonID = id;
}
}
Where buttID is declared outside of the listener. This solution could be improved by moving the listener outside of the class as a separate class to avoid memory leaks.
The other method for handling leakfree listeners would to define the listener as a nested class by declaring it public/private static class Listener
inside of the containing class, but this would cause int id
to get overwritten every time in this case.
精彩评论