tags:

views:

44

answers:

2

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)

A: 

You need not repeat same code for all. You can try out a generic listener, like :

private OnClickListener mCorkyListener = new OnClickListener() { 
    public void Click(View v) {
            // do something
    } 
}; 

Then all you have to do is register all three buttons to use this mCorkyListener. That is, inside onCreate(),

Button firstbtn  = (Button) findViewById(R.id.firstbtn); 
Button secondbtn = (Button) findViewById(R.id.secondbtn); 
Button thirdbtn  = (Button) findViewById(R.id.thirdbtn); 

firstbtn.setOnClickListener(mCorkyListener);
secondbtn.setOnClickListener(mCorkyListener);
thirdbtn.setOnClickListener(mCorkyListener);
kiki
No need to assign variables unless you're going to re-use them for something else: `(Button)findViewById(R.id.firstbtn)).setOnClickListener(mCorkyListener);`
Blrfl
Ok so there is no way of getting button objects other than findViewBId(id) ?? I was thinking there might be a way to get all buttons in layout as array of button objects and I can loop through it and add a listener to it , It will avoid adding Java code each time I add button in XML.
sat
I am not aware how to create your array of Buttons. Anyways, you can know which Button was clicked inside your mCorkyListener by using view.getId()
kiki
A: 

Look here for code samples. You have to use findViewById to "find" you r buttons though.

Asahi
It was partly helpful , I was wondering how to match View.getId() which is an integer with id name used in xml , understood after seeing the example. Thanks, but still searching for answer which is more generic. like get all btns as array of objects without using id and loop and attach listener to it.
sat