Reputation: 840
I have 25 buttons in my Layout. What is the efficient way to know which button is clicked or to get their IDs ??
Thanks in advance..
Upvotes: 0
Views: 449
Reputation: 6797
i don't get where is problem
in layout xml add onClick="onClick" for every button then in Activity ad function
public void onClick(View v) {
switch(v.getId()){
case R.id.Button1:
break;
case R.id.Button2:
break;
case R.id.Button3:
break;
//....
}
}
EDIT (coz i can't add coment to someone else answer: @Zach Rattner
According to this http://developer.android.com/reference/android/widget/Button.html Zach you're wrong
However, instead of applying an OnClickListener to the button in your activity, you can assign a method to your button in the XML layout, using the android:onClick attribute
Upvotes: 0
Reputation: 47183
The standard way to do this is to declare every button with a unique id in XML layout file, like this:
<Button android:id="@+id/my_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/>
Note that you have to do this for every button.
Next, you can use the following piece of code as button listeners:
final Button button1 = (Button) findViewById(R.id.my_button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
This will be inefficient since you'll be creating 25 new View.OnClickListener
objects (one for each button), and since you're programming for Android which is a memory constrained device, it will be better to create just one listener and assign it to every button, and then check which button does View v
correspond to.
I hope you're not going to put 25 buttons on one screen. If yes, you might want to rethink your design.
Upvotes: 0
Reputation: 2583
Something like this should work:
Button button1 = (Button)findViewById(R.id.Button01);
Button button2 = (Button)findViewById(R.id.Button02);
private class myListener implements OnClickListener
{
@Override
public void onClick(View arg0) {
if (arg0 == button1)
{
//button 1 clicked
}
else if (arg0 == button2)
{
//button 2 clicked
}
//etc
}
}
myListener listener = new myListener();
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
Upvotes: 0
Reputation: 21333
According to the Android documentation for an Activity, the only way to find a view is through findViewById. If you want to do something when a button with a specific ID is set, then you will have to add onClickListeners to each button individually.
Upvotes: 0
Reputation: 48871
Button implements View.OnClickListener which receives the view that has been clicked. You can get the ID as follows...
@Override
public void onClick(View view) {
int Id = view.getId();
}
Upvotes: 1