android-studio
  1. android-studio-radiobutton

Android Studio - RadioButton

Radiobuttons are UI elements in Android used to display a group of options where the user can select only one option at a time. In this article, we will learn how to use Radiobuttons in Android Studio.

Syntax

<RadioButton
    android:id="@+id/radioButtonId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Option"
    android:checked="true/false"/>

Example

Let's create a simple layout containing Radiobuttons to choose a fruit.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Select your favorite fruit:"/>

   <RadioGroup
       android:id="@+id/radioGroup"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

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

       <RadioButton
           android:id="@+id/orangeRadioButton"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Orange"/>

       <RadioButton
           android:id="@+id/bananaRadioButton"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Banana"/>
   </RadioGroup>

</LinearLayout>

Output

When you run the app, you will see the following layout:

Radiobutton output

Explanation

The code above creates a layout containing a TextView and a RadioGroup which contains three RadioButtons for the fruits - Apple, Orange, and Banana. By default, the Apple RadioButton is checked, and the user can only select one option.

Use

We can use RadioButton to create a group of options where only one option can be selected by the user. This can be used in any scenario where a user needs to choose only one option from a given number of options like online forms, surveys, quizzes, etc.

Important Points

  • We must wrap RadioButton elements inside a RadioGroup to enable selection of only one option at a time.
  • The android:checked attribute can be used to set the default value of a RadioButton checked or unchecked.

Summary

We learned how to use Radiobuttons in Android Studio and understand the associated syntax and attributes. We also saw examples of creating a simple layout that uses Radiobuttons to display a list of options.

Published on: