我是android开发的新手。我想在 java 类中以编程方式创建 RadioButton 组并将文本设置为单个单选按钮。请对此提供帮助
提前致谢。
给你了...
ln = (LinearLayout)findViewById(R.id.Linear_layout); // Assuming linearLayout is your parent layout
RadioGroup rg = new RadioGroup(context); // create the RadioGroup
rg.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f));
cg_Value = new String{“item 1”, “item 2”, “item 3”};
rb = new RadioButton[cg_Value.length];
rg.setOrientation(RadioGroup.HORIZONTAL);// horizontal or vertical depends on requirement
for (int l = 0; l < cg_Value.length; l++) {
rb[l] = new RadioButton(context);
rg.addView(rb[l]); // the RadioButtons are added to
// the radioGroup instead of the
// layout
rb[l].setTextColor(Color.BLACK);
rb[l].setText(cg_Value[l]);
rb[l].setTextSize(14);
}
//rb[1].setChecked(true);
ln.addView(rg);
希望这可以帮助
此程序块显示如何以编程方式创建 RadioButton 组。
希望它会帮助你。
public class RadioGroupActivity extends Activity {
protected static final String TAG = "RadioGroupActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radiogroup);
RadioGroup radGrp = (RadioGroup)findViewById(R.id.radGrp);
int checkedRadioButtonID = radGrp.getCheckedRadioButtonId();
radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup arg0, int id) {
switch(id) {
case -1:
Log.v(TAG, "Choices cleared!");
break;
case R.id.chRBtn:
Log.v(TAG, "Chose Chicken");
break;
case R.id.fishRBtn:
Log.v(TAG, "Chose Fish");
break;
case R.id.stkRBtn:
Log.v(TAG, "Chose Steak");
break;
default:
Log.v(TAG, "Huh?");
break;
}
}});
}
}