i need to know, how to recognize, which button is pressed. Like if i have two buttons ,say button 1 and button2,and both of them performing the same method, say method(),how to determine which button pressed ?
Regards
If you have more than one button click event, you can use switch case to identify which button is clicked. Link the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method. setOnClickListener takes an OnClickListener object as the parameter.
The android. widget. Button is subclass of TextView class and CompoundButton is the subclass of Button class. There are different types of buttons in android such as RadioButton, ToggleButton, CompoundButton etc.
Most ellegant pattern to follow:
public void onClick(View v) { switch(v.getId()) { case R.id.button_a_id: // handle button A click; break; case R.id.button_b_id: // handle button B click; break; default: throw new RuntimeException("Unknow button ID"); }
This way it's much simplier to debug it and makes sure you don't miss to handle any click.
I have 10 buttons performing the same method updateText()
, I used this code to get the clicked button's text:
public void updateText(View v){ Button btn = (Button) findViewById(v.getId()); String text = btn.getText().toString(); }
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