Android – generic listener for buttons in a layout of android

android

Scenario: I have three buttons defined in xml

<button android:id="@+id/firstbtn" 
    ...
/>
<button android:id="@+id/secbtn" 
    ...
/>
<button android:id="@+id/thirdbtn" 
    ...
/>
In Java one way to  listen to them is  
Button firstbtn = (Button) findViewById(R.id.firstbtn);  
    firstbtn.setOnClickListener(new View.OnClickListener() {  
            public void onClick(View v) {  
                Toast.makeText(getBaseContext(),   
                        "You have clicked first button",   
                        Toast.LENGTH_SHORT).show();  
            }  
        });  

for second btn , same code has to be repeated with different id ??
How can I make it generic enough that , it can listen to all buttons (say in for loop) and while handling I should be able to differentiate different btns. (may be get elements id)

Best Solution

Instead of a huge set of findViewById calls I rather like to use the onClick="methodName" xml attribute. For example:

<LinearLayout ...>
  <Button android:text="1" onClick="onButtonClicked" clickable="true" />
  <Button android:text="2" onClick="onButtonClicked" clickable="true" />
  <Button android:text="3" onClick="onButtonClicked" clickable="true" />
  <Button android:text="4" onClick="onButtonClicked" clickable="true" />
</LinearLayout>

In the activity where the layout is shown just add a method

public void onButtonClicked(View v){
     // do whatever needs to be done. For example:
     Toast.makeText(getApplicationContext(), ((Button) v).getText() + " clicked", Toast.LENGTH_SHORT).show(); 
}

You can also put the onClick and clickable attributes into the res/styles.xml file to save even more typing:

<?xml version="1.0" encoding="UTF-8" ?>
<resources>
  <style name="clickable_button" >
    <item name="android:onClick" >onButtonClicked</item>
    <item name="android:clickable" >true</item>
  </style>
</resources>

Your layout is then simplified to

<LinearLayout ...>
  <Button android:text="1" style="@style/clickable_button" />
  <Button android:text="2" style="@style/clickable_button" />
  <Button android:text="3" style="@style/clickable_button" />
  <Button android:text="4" style="@style/clickable_button" />
</LinearLayout>