I have in 16 Button
s (numbers, plus, minus etc) in my layout XML file.
I'm wondering how to check which button was pressed.
My idea is, that I will for each button use onClick()
method but this method is a bit impractically, because I will have 16 of these onClick()
methods one for each Button.
Is there a more elegant way?
You can deal with them all in a single class that implements OnClickListener, or within the activity class if you like...
import android.view.View.OnClickListener;
public class MyActivity extends Activity implements OnClickListener {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonA = (Button) findViewById(R.id.buttonA);
buttonA.setOnClickListener(this);
Button buttonB = (Button) findViewById(R.id.buttonB);
buttonB.setOnClickListener(this);
}
//etc... etc...
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonA:
// do something
break;
case R.id.buttonB:
// do something else
break;
}
}
}
You can use one handler that you do not define as anonymous inner class, but in a separate class. onClick()
will get the view passed in and you can select from it.
public class MyActivity implements OnClickListener {
public void onClick(View v) {
Button b = (Button)v;
// do what you want
}
...
}
and then in your layout.xml just put for each button
<Button android:id=".."
android:onClick="onClick"
Sure. Create an array of your button-ids
and assign them the same listener (an implementation of View.OnClickListener
- defined as separate class, not as anonymous class) in a loop. In the listener you can check which is the pressed button (by comparing view
parameter in onClick()
method).
In activity:
MyOnClickListener myListener = new MyOnClickListener();
for (int id : buttonIdArray)
((Button)findViewById(id)).setOnClickListener(myListener);
In the onClick method:
int id = view.getId();
switch (id)
{
case ...:
// Do stuff
case ...:
// Do different stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With