Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine which button pressed on android

Tags:

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

like image 877
Shishir.bobby Avatar asked Aug 05 '10 06:08

Shishir.bobby


People also ask

How do I know which button is pressed Android?

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.

What is Android widget button?

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.


2 Answers

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.

like image 116
Paul Turchenko Avatar answered Sep 18 '22 11:09

Paul Turchenko


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(); } 
like image 37
adwairi Avatar answered Sep 20 '22 11:09

adwairi