Get text from a pressed button

How can I get the text with the button pressed? (Android)

I can get the text from the button:

String buttonText = button.getText(); 

I can get the id with the button pressed:

 int buttinID = view.getId(); 

At this moment, I canโ€™t find out how to get the text of the pressed button.

 public void onClick(View view) { // Get the text on the pressed button } 
+58
android
Apr 11 '11 at 11:45
source share
6 answers

The view you passed to onClick() is the button you're looking for.

 public void onClick(View v) { // 1) Possibly check for instance of first Button b = (Button)v; String buttonText = b.getText().toString(); } 

1) If you use a non-anonymous class like onClickListener , you can check the type of the view before casting it, as it may be something other than a button.

+152
Apr 11 '11 at 11:50
source share

If you are sure that the OnClickListener instance is applied to the Button, you can simply pass the resulting view to the button and get the text:

 public void onClick(View view){ Button b = (Button)view; String text = b.getText().toString(); } 
+7
Apr 11 2018-11-11T00:
source share

Try using:

 String buttonText = ((Button)v).getText().toString(); 
+4
Jan 20 '14 at 11:42 on
source share

Try it,

 Button btn=(Button)findViewById(R.id.btn); String btnText=btn.getText(); 
0
Dec 12 '17 at 9:10
source share

In Kotlin:

 myButton.setOnClickListener { doSomething((it as Button).text) } 

Note: this gets the button text in the form of CharSequence , which probably can use more places in the code. If you really need a string, then you can use .toString() .

0
Dec 23 '18 at 20:35
source share

Button btn = (Button) findViewById (R.id.btn);

String btnText = btn.getText (). ToString ();

later this btnText can be used

for example: if (btnText == "Text to compare")

0
May 21 '19 at 5:52
source share



All Articles