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
}
This question is related to
android
Try this,
Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText();
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")
Try to use:
String buttonText = ((Button)v).getText().toString();
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()
.
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();
}
Source: Stackoverflow.com