android动态json单选按钮只选择一个值

时间:2016-08-27 06:05:59

标签: java android

在这里,我尝试只检查一个单选按钮,但我有多个选中的单选按钮。我怎样才能实现只检查一个。

starRadioBtn = new RadioButton[starCount.size()];
                radioGroup = new RadioGroup(StarCountActivity.this);
                radioGroup.setId(1);
                radioGroup.setOrientation(RadioGroup.VERTICAL);

            for (int i = 0;i<starCount.size(); i++){
                starRadioBtn[i] = new RadioButton(StarCountActivity.this);
                object = starCount.get(i);
                starRadioBtn[i].setText(object.getName());
                starRadioBtn[i].setId(i);
                radioGroup.addView(starRadioBtn[i]);
            }
            radioLayout.addView(radioGroup);

3 个答案:

答案 0 :(得分:2)

试试这个 xml布局

 <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <RadioGroup
            android:id="@+id/radiogroup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:orientation="vertical" />
    </LinearLayout>

我的活动代码

RadioGroup rg = (RadioGroup) findViewById(R.id.radiogroup);
RadioButton[] rb = new RadioButton[items.size()];
for (int i = 0; i < items.size(); i++) {
rb[i] = new RadioButton(this);
rg.addView(rb[i]);
rb[i].setText(items.get(i).getName());
}

答案 1 :(得分:1)

你能试试这段代码吗?

for (int row = 0; row < 1; row++) {
for (int i = 0;i<starCount.size(); i++){
            starRadioBtn[i] = new RadioButton(StarCountActivity.this);
            object = starCount.get(i);
            starRadioBtn[i].setText(object.getName());
            starRadioBtn[i].setId(i);
            radioGroup.addView(starRadioBtn[i]);
        }
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {});
}

答案 2 :(得分:1)

  

注意:删除此

 radioGroup.setId(1);

<强>码...

   radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup rg, int checkedId) {
            for(int i=0; i<rg.getChildCount(); i++) {
                RadioButton btn = (RadioButton) rg.getChildAt(i);
                if(btn.getId() == checkedId) {
                    String text = btn.getText().toString();
                    // do something with text
                    Toast.makeText(demo.this,text,Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }
    });