0

我是android开发的新手。我想在 java 类中以编程方式创建 RadioButton 组并将文本设置为单个单选按钮。请对此提供帮助

提前致谢。

4

3 回答 3

0

给你了...

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);

希望这可以帮助

于 2013-05-12T14:25:40.327 回答
0

此程序块显示如何以编程方式创建 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;
                }
            }});
    }

}

于 2013-05-12T14:20:10.980 回答
0

你在这里有很好的例子:

以编程方式创建 RadioButtons

或者这个例子也很好:

以编程方式添加的 RadioButtons 拒绝服从 LayoutParams 加权

于 2013-05-12T14:23:57.697 回答