Reputation: 31
I have a RadioGroup that contains 4 RadioButtons. They all call the same method when clicked, I know how to get the text that is associated with the button, but I can't figure out how to get the NAME of the button that is selected.
Surely there must be a way?
Thanks for the help
Upvotes: 1
Views: 140
Reputation: 1243
perhaps this could help you on the way:
// radioGroup - you need to set this after creating the radiogroup, by findViewById done in the right place or just assigning upon creating it, depending on how you create your layouts.
RadioButton radioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
String text = radioButton.getText().toString();
let me know if it works :) Always eager to learn and help !
Upvotes: 1
Reputation: 48871
I'm assuming you're using View.OnClickListener
for each RadioButton
. Correct?
If so don't do that. The easiest way to handle RadioButton
clicks is to use RadioGroup.OnCheckedChangeListener
instead.
In your onCreate(...)
after the call to setContentView(...)
find the RadioGroup
...
RadioGroup rg = (RadioGroup) findViewById(R.id.my_rg);
rg.setOnCheckedChangeListener(...);
The onCheckedChanged
listener looks like this...
public void onCheckedChanged(RadioGroup group, int checkedId)
...so in the listener simply do the following...
RadioButton radioButton = (RadioButton) findViewById(checkedId);
String text = radioButton.getText();
Upvotes: 0
Reputation: 34775
you can use a switch case to do so and onclick just compare with view.getId() with each id of radiobutton and then do the need full fetching of button name.
Below is the sample code::
switch (checkedRadioButton) {
case R.id.radiobutton1 : radioButtonSelected = "radiobutton1";
break;
case R.id.radiobutton2 : radioButtonSelected = "radiobutton2";
break;
case R.id.radiobutton3 : radioButtonSelected = "radiobutton3";
break;
}
using the LINK
or you can use the below code also
RadioGroup rg = (RadioGroup)findViewById(R.id.radiogroup);
RadioButton radioButton = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
Log.d("checked",radioButton.getText().toString());
Upvotes: 0