1

my button has a string id

<RadioButton 
android:id="@+id/Dirty" 
android:text="Very Dirty" 

and I would like to use the name Dirty in my code but I cant use get Text since the display name of the radio button is different from what I need and get Id returns an integer.

Any suggestions on how to get the "Dirty" from my selected radio button?

Thanks.

Code (from comments)

RadioButton rb = (RadioButton) findViewById(selectedId); 
String sel = (String) rb.getText();
Jonathan
  • 20,053
  • 6
  • 63
  • 70
user3170
  • 61
  • 2
  • 8

7 Answers7

6

Use getResourceEntryName method :

    RadioButton myButton = (RadioButton) findViewById(R.id.button1);
    String s = myButton.getResources().getResourceEntryName(R.id.button1);
Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
0

for getting name of a component use getName() . I think this will help ?

recursion
  • 354
  • 6
  • 11
0

Try this set tag to your radio button and get that tag in you java class

Xml

android:tag="Dirty"

Src

rb.getTag().toString();
Vaibhav Agarwal
  • 4,499
  • 3
  • 19
  • 20
0

A workaround would be to add a tag with the same name as id to your radio button (in addition to id):

<RadioButton
    android:id="@+id/Dirty"
    android:tag="Dirty"
    android:text="Very Dirty"
    />

Then in your code you can get the tag as String:

RadioButton radioButton = (RadioButton)findViewById(R.id.Dirty);
String tag = (String) radioButton.getTag();

So the inconvenience would be to add tags to your radio buttons, which are the same as their id.

Melquiades
  • 8,496
  • 1
  • 31
  • 46
0

If you want to use a string to refer at your button, you should use Tag instead of Id.

MikeKeepsOnShine
  • 1,730
  • 4
  • 23
  • 35
0

I think you can find the answer here.

This one

getResources().getResourceName(int resid);

seems to be useful for you.

Community
  • 1
  • 1
HAL9000
  • 3,562
  • 3
  • 25
  • 47
-1

Try this:

int selectedRdBtnId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(selectedRdBtnId);
String rbText = radioButton.getText();

Edit:

For getting id, I would suggest implementing onCheckedChangeListener.

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int radioButtonID) {
       //radioButtonID contains selected radio button's ID.

       case R.id.dirty:
           //do something
           break;
       case R.id.clean:
           //something else
           break;
       default:
           //default action
           break;
    }
});

Hope this helps.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
  • the getText just returns the display name of the button and not the id name of the button. – user3170 Dec 17 '13 at 08:40
  • The thing is that I know which radio button is selected and I can get the id but the id will always return an integer. I need the string name I gave to the button as an id. – user3170 Dec 17 '13 at 08:46