【问题标题】:Code-generated radiobuttons check selection代码生成的单选按钮检查选择
【发布时间】:2018-10-13 21:39:05
【问题描述】:

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

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 方法中做到这一点吗?我想将每个选定单选按钮的文本放在一个列表中。

谢谢。

【问题讨论】:

    标签: android button dynamic radio generated


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多