动态添加时如何检查RadioButton?

时间:2017-03-02 09:20:27

标签: android radio-button radio-group

在我的应用程序中,我根据需要动态添加RadioButton。 以下是代码:

RadioGroup rg = new RadioGroup(StartExamActivity.this);
            View v = new View(StartExamActivity.this);
            v.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
            v.setBackgroundColor(Color.parseColor("#3593D4"));
            rg.setLayoutParams(new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            rg.setOrientation(LinearLayout.VERTICAL);
            for (int i = 0; i < list.size(); i++) {
                rdbtn[i] = new RadioButton(StartExamActivity.this);
                rdbtn[i].setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT, 1f));
                rdbtn[i].setId(i);
                rdbtn[i].setText(list.get(i));
                final String value = rdbtn[i].getText().toString();

                rdbtn[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        if (value.equalsIgnoreCase(answer)) {
                            marks = marks + 2;
                        }
                    }
                });
                rg.addView(rdbtn[i]);
            }
            questionContainer.addView(rg);

现在我想将标记的值仅增加2,即使多次检查RadioButton也是如此。为此,我想知道RadioButton是否被选中。 怎么做??

请帮助!!

1 个答案:

答案 0 :(得分:1)

简单的事,

为什么不使用OnClickListener代替onCheckedChanged&gt;

rdbtn[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                        if(isChecked) {
                           // Write your logic here...
                        }
                    });