title: Dynamically adding buttons in android, how to add onClick to xml
body: <p>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 </p>
  
  <p>button.setOnClickListener(new OnClickListener(){....});</p>
  
  <p>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):</p>
  
  <p>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
                  }
              });</p>