Search code examples
androidradio-buttonandroid-radiogroup

RadioButton.setText() is not displaying the text


I am creating RadioButtons and adding them to RadioGroup dynamically. But the text for the RadioButtons are not showing on the screen when I run the application.

This is my code for RadioButtons

else if ((items.get(i).toString()).equals("rad")) {
                RadioGroup bg = new RadioGroup(getApplicationContext());
                int child=0;
                for (int h = textlen; h < text.size(); textlen++) {

                    if (text.get(textlen).contains("(")) {

                        s = text.get(textlen).replace("(", "");

                        if (s.contains(")"))
                            s = s.replace(")", "");

                    } else if (text.get(textlen).contains(")")) {
                        s = text.get(textlen).replace(")", "");
                    } else
                        s = text.get(textlen);

                    RadioButton radioButton = new RadioButton(
                            getApplicationContext());
                    bg.addView(radioButton);
                    // / radioButton.setName("rbt");
                    if (s.contains("{on}")) {
                    //  radioButton.setSelected(true);
                        radioButton.setChecked(true);
                        s = s.replace("{on}", "");
                    } else {
                        radioButton.setChecked(false);
                        s = s.replace("{of}", "");
                    }
                    //((RadioButton)bg.getChildAt(child)).setText(s);
                    //child++;

                    radioButton.setText(s);

                    String c = text.get(textlen).substring(
                            text.get(textlen).length() - 1);
                    if (c.equals(")")) {
                        textlen++;
                        break;
                    }



                }

                layout.addView(bg);
            }

When I debug the code I can see that the text is added to RadioGropus children

But on running the application the text is not visible. Can any one please detect the issue. Thanks Alot


Solution

  • Simply add

    setLayoutParams(params);
    

    for both RadioButton as well as RadioGroup.

    Where

    android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);