Search code examples
androidandroid-radiogroupandroid-radiobutton

Using RelativeLayout inside RadioGroup make RadioButtons not exclusive


I'm trying to make a RadioGroup with two radio buttons in the horizontal and vertical center. But also I want that they stay aligned by they radio since they had different text length. I used this code, but they are not mutually exclusive :

      <RadioGroup
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center|center_vertical">

                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/rbtn_gps_to"
                    android:text="to"
                    android:checked="true"
                    />


                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/rbtn_gps_from"
                    android:text="from"
                    android:layout_below="@+id/rbtn_gps_to"
                    />


            </RelativeLayout>


        </RadioGroup>

It works, both are aligned as I wish , but the problem is that when I check one and then I check the other , the first one stay also checked, so they are not exclusive. When I remove the Relative Layout the radiobuttons are exclusive. Is any way to create the layout that I want and the radiobuttons remain exclusive?


Solution

  • Previous answers contains some issue. The dots to selected are not in one column, they are not aligned. This is solution which looks the same like your.

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
        <RadioGroup
                android:layout_width=" wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:orientation="vertical">
            <RadioButton android:id="@+id/rbtn_gps_to"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:text="to"/>
            <RadioButton android:id="@+id/rbtn_gps_from"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:text="from"/>
        </RadioGroup>
    </RelativeLayout>