代码生成的radiobuttons检查选择

时间:2018-05-03 14:19:22

标签: android button dynamic radio generated

我有一些代码在活动中生成一些radiobuttons:

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);
}

目前,此按钮的作用是仅在视图中加载下一组radiobutton并删除当前的那些,但我不会检查哪些是被选中的。你知道我怎么能用onAddAnswer方法做到这一点吗?我想把每个选定的radiobutton的文本放在一个列表中。

感谢。

1 个答案:

答案 0 :(得分:0)

我设法自己解决这个问题。这就是我所做的:

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匹配,并检查是否有(或没有)任何选择的单选按钮。如果是,那么我找出哪一个。