J. Maes
J. Maes

Reputation: 6892

Get text from pressed button

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
}

Upvotes: 72

Views: 147419

Answers (8)

Atharva Swami
Atharva Swami

Reputation: 11

// Import text from button to string
String b_text = button.getText().toString();
// To set button text
button.setText("xyz");

Upvotes: 1

Codemaker2015
Codemaker2015

Reputation: 15705

Typecast the view into a button and access the text content using getText().

   public String onClick(View view) {
        // Get the text on the pressed button
        return ((Button)view).getText().toString()
    }

Upvotes: 1

Rama
Rama

Reputation: 195

Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText().toString();

Later this btnText can be used .

For example:

if(btnText == "Text for comparison")

Upvotes: 3

Anonsage
Anonsage

Reputation: 8320

In Kotlin:

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

Note: This gets the button text as a CharSequence, which more places in code can likely use. If you really want a String from there, then you can use .toString().

Upvotes: 4

Android Geek
Android Geek

Reputation: 636

Try this,

Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText();

Upvotes: 5

Amol Dale
Amol Dale

Reputation: 231

Try to use:

String buttonText = ((Button)v).getText().toString();

Upvotes: 8

Heiko Rupp
Heiko Rupp

Reputation: 30994

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.

Upvotes: 181

Zsombor Erdődy-Nagy
Zsombor Erdődy-Nagy

Reputation: 16914

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();
}

Upvotes: 8

Related Questions