Search code examples
javaandroidxmlkotlinradio-button

Android: Align the radio button inside radio group to center-horizontal


I have an item that consist of Radio Group which has 2 radio button with horizontal orientation.

enter image description here

This is the XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/ll_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="@drawable/bg_border"
    android:orientation="horizontal">

    <RadioGroup
        android:id="@+id/rg_answer_truefalse"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:padding="0dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rb_answer_true"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"
            android:background="@drawable/bg_border" />

        <RadioButton
            android:id="@+id/rb_answer_false"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"
            android:background="@drawable/bg_border" />
    </RadioGroup>

</LinearLayout>




The question is how to make each of the radio button centered horizontally? I've tried using layout_gravity or gravity as center or center_horizontal but it seems not working. Thanks


Solution

  • Here is the working solution. Not perfect but working.

    <RadioGroup
        android:id="@+id/rg_answer_truefalse"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:weightSum="5">
            <View
                android:layout_height="1dp"
                android:layout_weight="1"
                android:layout_width="0dp" />
            
            <RadioButton
                android:id="@+id/rb_answer_true"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_width="0dp" />
            
            <View
                android:layout_height="1dp"
                android:layout_weight="1"
                android:layout_width="0dp" />
            
            <RadioButton
                android:id="@+id/rb_answer_false"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_width="0dp" />
            
            <View
                android:layout_height="1dp"
                android:layout_weight="1"
                android:layout_width="0dp" />
    </RadioGroup>