Search code examples
androidandroid-radiogroupandroid-radiobutton

Align radio buttons by their checkradio


I'm using two radio buttons inside a radiogroup one below the other. THe upper button has as text "to" and the other has "from". What I want is that both will be in the center but they will be aligned by their checkradio. I tried this :

<RadioGroup
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:id="@+id/rgroup_pk"
                android:gravity="center">

                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/rbtn_to"
                    android:text="@string/title_to"
                    android:checked="true"
                    android:gravity="center|center_vertical" />


                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/rbtn_from"
                    android:text="@string/title_from"
                    android:gravity="center|center_vertical" />

            </RadioGroup>

THis makes the buttons stay in the vertical and horizontal center, but because of their text has different size what it shows is this (if "x" is the checkradio):

                   X to
                  X from

And what I want is this:

                   x to
                   x from

Solution

  • Include the RadioButtons in a RelativeLayout.

        <RadioGroup
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/rgroup_pk"
            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_to"
                     android:text="TO"
                     android:checked="true"/>
    
                <RadioButton
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:id="@+id/rbtn_from"
                     android:text="FROM"
                     android:layout_below="@+id/rbtn_to"/>
            </RelativeLayout>
        </RadioGroup>
    

    Notice the android:layout_below="@+id/rbtn_to". This, as the name suggest, places the second RadioButton below the first and not overlap it like is normal in a RelativeLayout.