Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text from pressed button

Tags:

android

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

I can get the text from a button:

String buttonText = button.getText(); 

I can get the id from a pressed button:

int buttinID = view.getId(); 

What I can't find out at this moment is how to get the text on the pressed button.

public void onClick(View view) {   // Get the text on the pressed button } 
like image 414
J. Maes Avatar asked Apr 11 '11 11:04

J. Maes


People also ask

How to getText of clicked button in android?

String buttonText = button. getText();

How do I get button text on Kotlin?

To set Android Button text, we can assign android:text XML attribute for Button in layout file with the required Text value. To programmatically set or change Android Button text, we can pass specified string to the method Button. setText(new_string_value).

How to get button text in Java android Studio?

If you have a button in your android app and you have set a onClickListner on it and after it is being clicked you need to know what is the text on the button set in the layout. xml follow the below code. (Button) v). getText(); can get you the text on the button.


2 Answers

The view you get passed in on onClick() is the Button you are 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 are using a non-anonymous class as onClickListener, you may want to check for the type of the view before casting it, as it may be something different than a Button.

like image 168
Heiko Rupp Avatar answered Oct 23 '22 10:10

Heiko Rupp


If you're sure that the OnClickListener instance is applied to a Button, then you could just cast the received view to a Button and get the text:

public void onClick(View view){ Button b = (Button)view; String text = b.getText().toString(); } 
like image 24
Zsombor Erdődy-Nagy Avatar answered Oct 23 '22 10:10

Zsombor Erdődy-Nagy