首页 > 解决方案 > 代码生成的单选按钮检查选择

问题描述

我有一些代码在活动中生成一些单选按钮:

public void drawRAnswers(int pst){
    int drawables = qmclist.get(pst).getAnswers().size();
    RadioGroup l1 = new RadioGroup(this);
    l1.setOrientation(LinearLayout.VERTICAL);
    for (int i=0;i<drawables;i++){
        RadioButton rd = new RadioButton(this);
        rd.setId(i);
        rd.setText(current.getAnswers().get(i).getAns());
        l1.addView(rd);
    }
    parentLinearLayout.addView(l1, parentLinearLayout.getChildCount());
}

我想要做的是能够验证单击按钮时检查了哪些(单选按钮):

public void onAddAnswer(View v){
    position++;
    delete();
    drawRAnswers(position);
}

现在,这个按钮所做的只是在视图中加载下一组单选按钮并删除当前单选按钮,但我不检查哪些单选按钮被选中。你知道我怎么能用这种onAddAnswer方法做到这一点吗?我想将每个选定单选按钮的文本放在一个列表中。

谢谢。

标签: androidbuttondynamicradiogenerated

解决方案


我自己设法弄清楚了这一点。这是我所做的:

public class Activity extends AppCompatActivity {
    RadioGroup currentGroup;
    ...
    public void onAddAnswer(View v){

    if (currentGroup.getCheckedRadioButtonId()==-1){
        Toast.makeText(getApplicationContext(), "Veuillez sélectionner au moins une réponse",
                Toast.LENGTH_LONG).show();
    } else {
        int selectedId = currentGroup.getCheckedRadioButtonId();
        RadioButton selectedRadio = (RadioButton)findViewById(selectedId);
        Toast.makeText(getApplicationContext(), selectedRadio.getText().toString()+" is selected",
                Toast.LENGTH_SHORT).show();
        position++;
        delete();
        updateData(position);
    }
}
    ...
    public void drawRAnswers(int pst){
    int drawables = qmclist.get(pst).getAnswers().size();
    RadioGroup l1 = new RadioGroup(this);
    currentGroup = l1;
    l1.setOrientation(LinearLayout.VERTICAL);
    for (int i=0;i<drawables;i++){
        RadioButton rd = new RadioButton(this);
        rd.setId(i);
        rd.setText(current.getAnswers().get(i).getAns());
        l1.addView(rd);
    }
    parentLinearLayout.addView(l1, parentLinearLayout.getChildCount());
}
}

所以基本上我所做的是每次我绘制单选按钮时都有一个 RadioGroup,将它与 currentGroup 匹配并检查我是否选择了(或没有)任何单选按钮。如果是,那么我找出哪个。


推荐阅读