I have a button's onClickListener that needs to detect which radiobutton was selected when the user clicks the button. Currently, the Log.v you see below in the onClickListener is not returning a useless bit of info:
This is clicking submit three times with a different radio selected each time:
04-27 19:24:42.417: V/submit(1564): 1094168584
04-27 19:24:45.048: V/submit(1564): 1094167752
04-27 19:24:47.348: V/submit(1564): 1094211304
So, I need to know which radioButton is actually selected - is there a way to get the object of the radiobutton? I want to be able to get it's id# from XML, as well as its current text.
Here's the relevant code:
public void buildQuestions(JSONObject question) throws JSONException {
radioGroup = (RadioGroup) questionBox.findViewById(R.id.responseRadioGroup);
Button chartsButton = (Button) questionBox.findViewById(R.id.chartsButton);
chartsButton.setTag(question);
Button submitButton = (Button) questionBox.findViewById(R.id.submitButton);
chartsButton.setOnClickListener(chartsListener);
submitButton.setOnClickListener(submitListener);
TagObj tagObj = new TagObj(question, radioGroup);
submitButton.setTag(tagObj);
}
public OnClickListener submitListener = new OnClickListener() {
public void onClick(View v) {
userFunctions = new UserFunctions();
if (userFunctions.isUserLoggedIn(activity)) {
TagObj tagObject = (TagObj) v.getTag();
RadioGroup radioGroup = tagObject.getRadioGroup();
JSONObject question = tagObject.getQuestion();
Log.v("submit", Integer.toString(radioGroup.getCheckedRadioButtonId()));
SubmitTask submitTask = new SubmitTask((Polling) activity, question);
submitTask.execute();
}
}
};
getCheckedRadioButtonId()
returns theid
of theRadioButton
(or-1
if noRadioButtons
are checked) that is checked in theRadiogroup
. If you set distinct ids to theRadioButons
in the layout then you will try to match those ids with the return of the method to see which one is checked:I think relying on what
radioGroup.getCheckedRadioButtonId()
returns is not good practice if you want to store it into the database or to use it.Because:
getCheckedRadioButtonId()
value will keep changing for eachRadioButton
and if there are two similar values (two views in the same hierarchy) Android will choose the first one. Unless you provided a unique Ids with methodgenerateViewId()
and set it to the view withsetId()
.getCheckedRadioButtonId()
will return unknown value.Therefore
Switching on
radioGroup.getCheckedRadioButtonId()
and implement your custom values to each selection then use that custom value, not the View Id.Example to use values from selected Radio Button:
Example to populate selected RadioButton to UI:
store the checked ID, then compare it to each button using the function radioButton.getID() using a switch statement or if-else chains