tags:

views:

63

answers:

2

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?

A: 

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);
    }
alex
So for a large grid (talking 10x10), you would just use a for loop and cycle through checking the references? Should I be worried about any performance hit for this? Thanks for your help.
Hemmer
This kind of checks should be blazingly fast.
alex
+1  A: 

Hi,

You can manually set an ID for dynamically created widgets by this method.

ognian
Thanks, this is exactly what I was looking for.
Hemmer