Q: Dynamically adding buttons in android, how to add onClick to xml Here's the situation: I have an activity that dynamically generates a bunch of randomized  custom imagebuttons and adds them to TableRows, in a TableView, in my xml. This activity also has a method that I want to call when one/any of these buttons is clicked. The buttons have variables inside them; the method gets these variables and sets them into a TextView (in the same activity) so I figure all the buttons can use this one method. If these buttons were defined in the XML I would just use android:onClick="displayCell" to specify the method, but they aren't. Is there a way to just set onClick for these buttons as I'm generating them in the activity or do I have to use 
button.setOnClickListener(new OnClickListener(){....});
and go through a bunch of hassle as I've seen in some of the answers around here? The problem I have with that is that I can't seem to call my method from inside onClick because the argument of the method (the button) is not final (I'm making a bunch of 'button' in a loop so I don't think it can be):
button.setOnClickListener(new OnClickListener(){
                public void onClick(View q){
                    button.getActivity().displayCell(button);//I want to do something like this but this obviously doesn't work
                }
            });

A: You can have the Activity implement OnClickListener and then (assuming you are in the activity):
button.setOnClickListener(this);


A: Yes as comodoro states, or make your onClickLIstener a member variable of your class, don't do a "new" on each button.
private OnClickListener mOnClickListener = new OnClickListener() {...};

and when creating your buttons:
button.setOnClickListener(mOnClickListener);

The onClick() function in your listener will be passed the View of the button itself.  You can access the buttons variables, etc, from this function.
public void onClick(View v)
{
 ImageButton button = (ImageButton)v;
 // and access your button data via button object...
}


A: A solution to this could be :


*

*Create different instances of buttons .(So you can make them final)

*Use setId() method to give them an integer ID (to refer to them later).You can store the ID's in an a Listto refer them later on. 

*Define their onClickListeners right after you create it.


A: Try using a class that inherits from button and add there the OnClickListener. Like this:
class MyButton extends Button {

        OnClickListener clicker = new OnClickListener() {
        public void onClick(View v) {

              displayCell(v);

        }
        };

}

