sriram
sriram

Reputation: 9052

All radio buttons are getting selected under a radio group, android

I'm very new to android and I have an xml like this:

<RadioGroup
        android:id="@+id/cardRadioGroup"
        android:layout_width="wrap_content"
        android:layout_height="45dp" android:layout_alignParentLeft="true" android:layout_marginLeft="35dp"
        android:layout_alignTop="@+id/cardEditText">
</RadioGroup>

I'm tyring to inflate this xml using my code to generate as many radio buttons I want depending on my data model.

The code I use is (which is inside a for loop) :

        LayoutInflater inflater = this.getLayoutInflater();
        View currentView = inflater.inflate(R.layout.card_payment_content_node,null);

        RadioGroup rg = (RadioGroup) currentView.findViewById(R.id.cardRadioGroup);
        RadioButton rb =  new RadioButton(this);
        //set radiobutton properties
        rb.setText(entry.getKey());
        rb.setId(++radioButtonIdCounter);

        rg.addView(rb);

        //add to view
        parent.addView(currentView);

This is working as expected. But the problem is that I can select many radio buttons at a time on my device.

I'm not sure why this is happening. Where I'm making the mistake?

Thanks in advance.

Upvotes: 2

Views: 3533

Answers (1)

class stacker
class stacker

Reputation: 5347

All of your buttons have the same ID. That's why they act so uniformly.

You would inflate the layout only once. You'd have to add the buttons programmatically by identifying cardRadioGroup and then looping in code, generating unique IDs for all buttons.

To add radio buttons to the group, use RadioGroup.addview().

To create the radio buttons, use one of the constructors of RadioButton and set further properties if required.

Upvotes: 7

Related Questions