簡體   English   中英

我已將無線電組動態添加到活動中。 我無法選擇哪個Radiogroup,但是可以看到Radiobutton

[英]I have dynamically added radiogroups to an Activity. I can't get which Radiogroup is selected, but I can see the 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;
                        }
                    }
                });

基本上,我已經完成了單選按鈕檢測的工作。 但是,我不知道選擇了哪條線(無線電組)。 必須有一種方法。 我嘗試使用getCheckedRadioButtonId()但是沒有用。

我希望有人可以幫助我。

嘗試設置布局參數的重力

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

您可以根據所使用的ViewGroup更改layoutparams的類型。

這樣嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM