简体   繁体   中英

Deselect dynamically generated radio buttons after selecting one radio button in android

I am generating the radio buttons dynamically from server returned json data in android.

I can display the radio buttons in radio group. Also can get id of each radio button.

But when I click on the next radio buttons all are stayed as selected. None of them are unchecked.

As the radio numbers are generated dynamically so it sizes will vary.

My code snippets :

if(type.equals("radio_buttons")){

        String optionName = regData.getOption();
        optionName = Character.toString(optionName.charAt(0)).toUpperCase()+optionName.substring(1);

        List listItem = new ArrayList();
        listItem.add(optionName);

        final RadioGroup rg = new RadioGroup(getActivity()); //create the RadioGroup
        rg.setOrientation(RadioGroup.HORIZONTAL);

        final int radioSize = listItem.size();
        final RadioButton[] rb = new RadioButton[radioSize];

        for(int i=0; i<radioSize; i++){
            rb[i]  = new RadioButton(getActivity());
            rg.addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout
            rb[i].setId(i);
            rb[i].setText(optionName);
        }

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                for(int j = 0; j<radioSize; j++){
                    rg.removeViewAt(checkedId);
                }
                /*
                switch (checkedId)
                {
                    case 1:
                        Toast.makeText(OnsiteRegistrationFragment.this.getActivity(), "VIEW ID " + checkedId, Toast.LENGTH_LONG).show();

                    case 2:
                        Toast.makeText(OnsiteRegistrationFragment.this.getActivity(), "VIEW ID " + checkedId, Toast.LENGTH_LONG).show();
                }*/
            }
        });

        this.linearLayout.addView(rg);
} 

How can i clear/uncheck the other radio buttons when one radio button is selected in android?

LinkedList<RadioButton> radiobuttons

At the time of creating button add radiobuttons in radiobuttons in your for loop.

for (int i = 0; i < radioSize.size(); i++) {
    RadioButton rb;
    rb = radiobuttons.get(i);
    rg.removeView(rb);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM