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

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RadioButton;

/**
*
* @author assortmentofsites
*/
public class multivalueRadioButton extends RadioButton{
String value;
String auxvalue;
public multivalueRadioButton(Context context) {
super(context);
}

public multivalueRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
}

public multivalueRadioButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setValue(String v) { this.value = v; }
public String getValue() { return this.value; }
public void setAuxValue(String v) { this.auxvalue = v; }
public String getAuxValue() { return this.auxvalue; }
}

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:


private RadioGroup inflateRg(RadioGroup rg, Cursor cursor) {

if (cursor.moveToFirst()) {
int i = 0;
do {
multivalueRadioButton rdbtn = new multivalueRadioButton(context);
rdbtn.setId(cursor.getInt(0)); //radio button id
rdbtn.setText(cursor.getString(1));//radio button name
rdbtn.setValue(cursor.getString(0));//extra value
rg.addView(rdbtn, i);
i++;
} while (cursor.moveToNext());
}
return rg;
}

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

Leave a Comment