2

我想动态地将无线电组添加到我的布局中,我可以这样做。我还可以用 Toast 显示选择了哪个单选按钮。

我唯一无法解决的问题是向广播组展示。

编码:

             final RadioButton[] rb = new RadioButton[3];
                final RadioGroup rg = new RadioGroup(getApplicationContext()); //create the RadioGroup
                rg.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
                for(int y=0; y<3; y++){
                    rb[y]  = new RadioButton(getApplicationContext());
                    rg.addView(rb[y]); //the RadioButtons are added to the radioGroup instead of the layout
                    if(y==0){
                        rb[0].setText("Chico");
                    }else{
                        if(y==1){
                            rb[1].setText("Mediano");
                        }else{
                            rb[2].setText("Grande");
                        }
                    }
                }



                rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {


                    public void onCheckedChanged(RadioGroup rGroup, int checkedId) {


                        int pos = rg.indexOfChild(findViewById(checkedId));
                        switch (pos)
                        {
                            case 0 :
                            Toast.makeText(getBaseContext(), "You have Clicked Radio 0", Toast.LENGTH_SHORT).show();
                        break;
                            case 1 :
                            Toast.makeText(getBaseContext(), "You have Clicked Radio 1", Toast.LENGTH_SHORT).show();
                        break;
                            case 2 :
                            Toast.makeText(getBaseContext(), "You have Clicked Radio 2", Toast.LENGTH_SHORT).show();
                        break;
                            default :
                            Toast.makeText(getBaseContext(), "Nothing Selected", Toast.LENGTH_SHORT).show();
                            break;
                        }
                    }
                });

基本上,我已经完成了单选按钮检测工作。但是,我不知道选择了哪条线路(无线电组)。必须有办法。我试过了,getCheckedRadioButtonId()但没有用。

我希望有人可以帮助我。

4

2 回答 2

0

尝试设置布局参数的重力

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.LEFT;
rg.setLayoutParams(lp);

您可以根据您使用的 ViewGroup 更改布局参数的类型。

于 2013-08-02T04:04:03.967 回答
0

像这样试试

int radioButtonID = rg.getCheckedRadioButtonId();
View radioButton = rg.findViewById(radioButtonID);
int index = rg.indexOfChild(radioButton);
于 2013-08-02T04:34:18.847 回答