androidandroid-layoutandroid-radiogroup

Android: Horizontal Center Align for Radio Group


I have Radio Group which appears left aligned on screen.
How can i horizontally center the radio group.
The TextView itself appears properly center-aligned horizontally.

....
        <LinearLayout
            android:id="@+id/LinearLayout02"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            >

            <TextView
                android:id="@+id/text1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center_horizontal"
                android:text="Test"
                />


        <RadioGroup
            android:id="@+id/radioGroupMode"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
            android:layout_gravity="center_horizontal"  
            android:gravity="center_horizontal" >

            <RadioButton
                android:id="@+id/radioTestMode"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:checked="true"
                android:tag="OPTION_1"
                android:text="Option1"
             />

            <RadioButton
                android:id="@+id/radioLearnMode"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:tag="Option_2"
                android:text="Option 2"
             />
        </RadioGroup>

</LinearLayout>
....

Solution

  • In radio group layout you mentioned layout width like match_parent,if you mention your parent layout like match parent you cannot use gravity properly.So you need to change width like wrap_content.

    <RadioGroup
                    android:id="@+id/radioGroupMode"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" 
                    android:layout_gravity="center_horizontal"  
                    android:gravity="center_horizontal" >
    
                    <RadioButton
                        android:id="@+id/radioTestMode"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:checked="true"
                        android:tag="OPTION_1"
                        android:text="Option1"
                     />
    
                    <RadioButton
                        android:id="@+id/radioLearnMode"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:tag="Option_2"
                        android:text="Option 2"
                     />
                </RadioGroup>