开发者

Android - Dynamic Radio Buttons Problem

开发者 https://www.devze.com 2023-03-05 22:22 出处:网络
Please help me out on this one, Im trying to produce 2 radio buttons in a for loop dynamically depending upon the user input waht i want is to have radio buttons like

Please help me out on this one, Im trying to produce 2 radio buttons in a for loop dynamically depending upon the user input waht i want is to have radio buttons like

*Radio Button1 *RadioButton2

*Radio Button1 *RadioButton2

*Radio Button1 *RadioButton2

*Radio Button1 *RadioBu开发者_开发技巧tton2

. . .

.

and so forth .. depending upon the loop !

Here is the snippet from my code its is working for only 2 radio buttons in one row only but when i increase the value of count . . i get android run time error of radiogroup child already having a parent. :S

List<RadioGroup> allradioGroup = new ArrayList<RadioGroup>();
RadioGroup radioGroup;

List<RadioButton> allRadio = new ArrayList<RadioButton>();
RadioButton radioButton;

        for (int i = 0; i < count; i++) {

        /* Defining RadioGroup */
        radioGroup = new RadioGroup(this);
        radioGroup.setOrientation(RadioGroup.HORIZONTAL);

        allradioGroup.add(radioGroup);


        /* Displaying Radio Buttons */
        for (int j = 0; j < 2; j++) {
            radioButton = new RadioButton(this);
            radioButton.setTextColor(getResources().getColor(R.color.grey));
            radioButton.setId((j + 100));

            allRadio.add(radioButton);

            if (allRadio.get(j).getId() == 100) {
                radioButton.setText("private");
            } else if (allRadio.get(j).getId() == 101) {
                radioButton.setText("public");
            }

                allradioGroup.get(i).addView(allRadio.get(j), j,
                        layoutParams);
        }

        linear.addView(allradioGroup.get(i));

    }

Please HELP. Thanks


Your problem is this line: "allradioGroup.get(i).addView(allRadio.get(j), j, layoutParams);"

The parameter j will be in the range 0-1, also when you create your second row. You are trying to use allRadio.get(j) which on the second run will return the first radio button you created (which already has a parent). To fix this, replace "j" with: "i*2+j". That should fix it.

0

精彩评论

暂无评论...
验证码 换一张
取 消