I would to create a number of radio button dinamically in a fragment, I only have problem with style. If I put radiobutton code in the xml file, default style is applied correctly, but when I create radiobutton through a function I see different style!
XML
<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:animationCache="false">
<RadioButton
android:text="RadioButton 1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/radioButton3" />
<RadioButton
android:text="RadioButton 2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/radioButton4" />
</RadioGroup>
RESULT
JAVA CODE
This code is put in onCreateView in the fragment
public void addRadioButton(Context ctx,int num){
RadioGroup radioGroup= (RadioGroup) alertInflatedView.findViewById(R.id.radiogroup);
for (int i = 1; i <= num; i++) {
RadioButton radioButton = new RadioButton(ctx);
radioButton.setId(1+i);
radioButton.setText("Radio " + radioButton.getId());
radioButton.setTextColor(getResources().getColor(R.color.black));
radioGroup.addView(radioButton);
}
}
RESULT
As you can see radio buttons have different style, someone could help me, if is possibile, to apply default style programmatically?
Open “res/layout/main. xml” file, add “RadioGroup“, “RadioButton” and a button, inside the LinearLayout . Radio button selected by default. To make a radio button is selected by default, put android:checked="true" within the RadioButton element.
You can check the current state of a radio button programmatically by using isChecked() method. This method returns a Boolean value either true or false. if it is checked then returns true otherwise returns false.
For creating dynamic RadioButton, we need to use android. view. ViewGroup. LayoutParams which configures the width and height of views and implements setOnCheckedChangeListener() method of RadioGroup class.
Use the android:orientation="horizontal" -attribute of the RadioGroup.
you have to create style on drawable or style.xml, as your requirement.
drawable/null_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@android:color/transparent" />
</selector>
Set each button to use it (and to center the text) like this (R.drawable.null_selector is selector XML):
Now, In your Activity, you must be implement such style.
RadioButton radioButton = new RadioButton(ctx);
radioButton.setText(Integer.toString(i));
radioButton.setGravity(Gravity.CENTER);
radioButton.setButtonDrawable(R.drawable.null_selector);
I think, this will help you for implementing custom style in Radio Button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With