Android radio button set mulptiple values

by admin on June 5, 2014

As i was working on an android app i released that i needed a radio button whose value was different from the display text. This is because the display text can be in any of several languages i.e Chinese, french, Japanese etc.

i extended the radio button class as below

01.import android.content.Context;
02.import android.util.AttributeSet;
03.import android.widget.RadioButton;
04. 
05./**
06.*
07.* @author assortmentofsites
08.*/
09.public class multivalueRadioButton extends RadioButton{
10.String value;
11.String auxvalue;
12.public multivalueRadioButton(Context context) {
13.super(context);
14.}
15. 
16.public multivalueRadioButton(Context context, AttributeSet attrs) {
17.super(context, attrs);
18.}
19. 
20.public multivalueRadioButton(Context context, AttributeSet attrs, int defStyle) {
21.super(context, attrs, defStyle);
22.}
23.public void setValue(String v) { this.value = v; }
24.public String getValue() { return this.value; }
25.public void setAuxValue(String v) { this.auxvalue = v; }
26.public String getAuxValue() { return this.auxvalue; }
27.}

the custom radio button “multivalueRadioButto” can captuer two extra vales i.e value and  auxvalue

you can save the code in a file like “multivalueRadioButton.java”

Usage:

if you are getting data from a database and creating the custom radio buttons on the fly you can use a function like one below:

01.private RadioGroup inflateRg(RadioGroup rg, Cursor cursor) {
02. 
03.if (cursor.moveToFirst()) {
04.int i = 0;
05.do {
06.multivalueRadioButton rdbtn = new multivalueRadioButton(context);
07.rdbtn.setId(cursor.getInt(0)); //radio button id
08.rdbtn.setText(cursor.getString(1));//radio button name
09.rdbtn.setValue(cursor.getString(0));//extra value
10.rg.addView(rdbtn, i);
11.i++;
12.} while (cursor.moveToNext());
13.}
14.return rg;
15.}

simply get the data from the database into a cursor, call this function and you will have your radio group populated :-)

Leave a Comment