我已经动态地将radiogroup添加到Activity中。我不能选择哪个Radiogroup,但我可以看到Radiobutton

时间:2013-08-02 03:35:47

标签: java android radio-button radio-group

我想动态地将无线电组添加到我的布局中,我可以这样做。此外,我还能够选择了一个选择了radiobutton的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;
                        }
                    }
                });

基本上,我已经完成了无线电按钮检测工作。但是,我不知道选择了哪一行(radiogroup)。必须要有办法。 我尝试使用getCheckedRadioButtonId(),但它没有用。

我希望有人可以帮助我。

2 个答案:

答案 0 :(得分:0)

尝试设置布局参数的重力

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

您可以根据您正在使用的ViewGroup更改布局面板的类型。

答案 1 :(得分:0)

试试这个,

int radioButtonID = rg.getCheckedRadioButtonId();
View radioButton = rg.findViewById(radioButtonID);
int index = rg.indexOfChild(radioButton);