Android
Android

Reputation: 133

How to check RadioButton is checked when added dynamically?

In my application I am adding RadioButton dynamically depending on requirement. Below is the code :

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

Now I want to increase the value of marks by 2 only ones even when RadioButton is checked multiple times. For that I want to know whether RadioButton is checked or not. How to do this??

Please Help!!

Upvotes: 0

Views: 230

Answers (1)

Paresh
Paresh

Reputation: 6857

Simple thing,

Why don't you use OnClickListener instead of onCheckedChanged>

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

Upvotes: 1

Related Questions