Search code examples
javaandroidxmlstyles

applying layout preferences to dynamically added buttons in android radiogroup


I tried to look into all the possible answers but really I cannot figure how to proceed. I'm creating radio buttons into a radiogroup dinamically

for (int i = 0; i < keys.length; i++) {
        final RadioButton rdbtn = new RadioButton(this);
        rdbtn.setId(View.generateViewId());
        rdbtn.setText(keys[i]);
        rdbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedWH = rdbtn.getText().toString();
            }
        });
        mRgAllButtons.addView(rdbtn);
    }

and I would like to apply this style to the buttons

<RadioButton

            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginStart="60dp"
            android:layout_marginEnd="60dp"
            android:background="@drawable/radio_pressed"
            android:button="@android:color/transparent"                
            android:textAlignment="center"
            android:textColor="@color/colorPrimary"
            android:textSize="18sp"
            android:textStyle="bold" />

Any help is really appreciated.


Solution

  • This is a simple way. You can create a RadioButton view instance from the XML so it will have the style that you want.

    1. Create XML layout with RadioButton element and the style - just what you have mentioned.
    2. Use that layout to create a new RadioButton View (and add it to the RadioGroup).

     LayoutInflater inflater = LayoutInflater.from(context);
    
     for (int i = 0; i < keys.length; i++) {
        final RadioButton rdbtn = inflater.inflate(R.layout.layout_name, mRgAllButtons, false);
        // mRgAllButtons - parent of this view.
        // attachToParent - false - add to the parent manually.
        rdbtn.setId(View.generateViewId());
        rdbtn.setText(keys[i]);
        rdbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedWH = rdbtn.getText().toString();
            }
        });
        mRgAllButtons.addView(rdbtn);
    }