Android Radio Button with example

Android-Radio-Button-with-example.png

21st February, 2023

RadioButton is a two-states user interface of the Android system that is either checked or unchecked. A Radio Button is usually used with a RadioGroup that allow the user to choose only one option from a set of values.

If a Radio Button is used as a standalone (without RadioGroup) and once it is checked, the user cannot uncheck it by clicking on it.

The android:checked attribute is used to change the state of the Radio Button. If we set android:checked=”true”, the radio button will be in the ON (checked) state. By default the Radio Button comes with the OFF (unchecked) state.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <!--Radio button with default state-->
    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RadioButton" />

    <!--Radio button with checked=true state-->
    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="RadioButton2" />

</LinearLayout>
Radio-Button-in-Android-example-1.png

1. Create Radio Button

We can create Android Radio Button in two ways:

1.1 Create Radio Button in XML layout file

Open the XML layout file in Android Studio. As we discussed earlier that Radio Button are generally used with RadioGroups, So select the RadioGroup from the palette and add it to the layout . Do the same to add Radio Buttons. See the code below.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:padding="10dp">


    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select Gender:" />

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

        <!--Radio Button-->
        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Male" />

        <!--Radio Button-->
        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Female" />

    </RadioGroup>
</LinearLayout>

1.2 Create Radio Button Programmatically in Android

Now let’s create an Android Radio Button in Kotlin or Java code. Create an object of the Android RadioButton class with a context parameter. Assign attributes according to your needs. Then add buttons to the RadioGroup. That’s it.

KotlinJava
content_copy light_mode remove
package com.androidchunk.helloradiobutton

import android.os.Bundle
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)

        val radioButton1 = RadioButton(this)
        radioButton1.text = "Good"

        val radioButton2 = RadioButton(this)
        radioButton2.text = "Better"

        val radioButton3 = RadioButton(this)
        radioButton3.text = "Best"

        radioGroup.addView(radioButton1)
        radioGroup.addView(radioButton2)
        radioGroup.addView(radioButton3)
    }
}
package com.androidchunk.helloradiobutton;

import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioGroup radioGroup = findViewById(R.id.radioGroup);

        RadioButton radioButton1 = new RadioButton(this);
        radioButton1.setText("Good");

        RadioButton radioButton2 = new RadioButton(this);
        radioButton2.setText("Better");

        RadioButton radioButton3 = new RadioButton(this);
        radioButton3.setText("Best");

        radioGroup.addView(radioButton1);
        radioGroup.addView(radioButton2);
        radioGroup.addView(radioButton3);
    }
}

2. Radio Button Event Handling

Following are some of the most commonly used events of Android Radio Button.

2.1 Android Radio Button Click Event Handling

2.1.1 Radio Button Click Event in layout file

To add a click listener statically, first create a method in Java or Kotlin code. Then assign the method name to Radio Button’s onClick attribute. See the code below.

KotlinJava
content_copy light_mode remove
package com.androidchunk.helloradiobutton

import android.os.Bundle
import android.view.View
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class TestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
    }

    //Clicking on the radio buttons will trigger this method
    fun onRadioButtonClicked(view: View?) {
        if (view is RadioButton && view.isChecked) {
            Toast.makeText(this, "Gender: " + view.text, Toast.LENGTH_SHORT).show()
        }
    }
}
package com.androidchunk.helloradiobutton;

import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

class TestActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
    }

    //Clicking on the radio buttons will trigger this method
    public void onRadioButtonClicked(View view) {
        if (view instanceof RadioButton && ((RadioButton) view).isChecked()) {
            Toast.makeText(this, "Gender: "+((RadioButton) view).getText(), Toast.LENGTH_SHORT).show();
        }
    }
}

Awesome, now assign the method to the android:onClick attribute of all the Radio Buttons.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:padding="10dp"
    tools:context=".TestActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select Gender:" />

    <!--Radio Group-->
    <RadioGroup
        android:id="@+id/genderRadioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!--Radio Button-->
        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked"
            android:text="Male" />

        <!--Radio Button-->
        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked"
            android:text="Female" />

    </RadioGroup>
</LinearLayout>

2.1.2 Radio Button Click Event in Kotlin/Java file (Runtime click listener)

We can also add a click listener at runtime. All we have to do is call setOnClickListener(View.OnClickListener) from the reference of the Radio Button. For example:

KotlinJava
content_copy light_mode remove
package com.androidchunk.helloradiobutton

import android.os.Bundle
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val radioButton1 = findViewById<RadioButton>(R.id.radioButton1)
        val radioButton2 = findViewById<RadioButton>(R.id.radioButton2)

        radioButton1.setOnClickListener {
            Toast.makeText(this@MainActivity,"Radio Button 1 clicked",Toast.LENGTH_SHORT).show()
        }

        radioButton2.setOnClickListener {
            Toast.makeText(this@MainActivity,"Radio Button 2 clicked",Toast.LENGTH_SHORT).show()
        }
    }
}
package com.androidchunk.helloradiobutton;

import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioButton radioButton1 = findViewById(R.id.radioButton1);
        RadioButton radioButton2 = findViewById(R.id.radioButton2);

        radioButton1.setOnClickListener(view -> {
            Toast.makeText(MainActivity.this, "Radio Button 1 clicked", Toast.LENGTH_SHORT).show();
        });

        radioButton2.setOnClickListener(view -> {
            Toast.makeText(MainActivity.this, "Radio Button 2 clicked", Toast.LENGTH_SHORT).show();
        });
    }
}

2.2 Android Radio Button Check Change Event Handling

The OnCheckedChanged event is used for Radio Button. This event is triggered when the state of the Radio Button is changes. Call the setOnCheckedChangeListener(OnCheckedChangeListener) method by the instance of the Radio Button to register onCheckedChanged event. See the example below.

KotlinJava
content_copy light_mode remove
package com.androidchunk.helloradiobutton

import android.os.Bundle
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val radioButton1 = findViewById<RadioButton>(R.id.radioButton1)
        val radioButton2 = findViewById<RadioButton>(R.id.radioButton2)

        radioButton1.setOnCheckedChangeListener { compoundButton, isChecked ->
            Toast.makeText(this@MainActivity,"radioButton1 checked: $isChecked",Toast.LENGTH_SHORT).show()
        }
        radioButton2.setOnCheckedChangeListener { compoundButton, isChecked ->
            Toast.makeText(this@MainActivity,"radioButton2 checked: $isChecked",Toast.LENGTH_SHORT).show()
        }
    }
}
package com.androidchunk.helloradiobutton;

import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioButton radioButton1 = findViewById(R.id.radioButton1);
        RadioButton radioButton2 = findViewById(R.id.radioButton2);

        radioButton1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                Toast.makeText(MainActivity.this, "radioButton1 checked: "+isChecked, Toast.LENGTH_SHORT).show();
            }
        });
        radioButton2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                Toast.makeText(MainActivity.this, "radioButton2 checked: "+isChecked, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

3. Radio Button Attributes

Attribute Description
android: id It is used to uniquely identify the Radio Button
android:width Sets the width of Radio Button
android:height Sets the height of Radio Button
android:checked It is used to specify the current state of Radio Button
android:onClick Name of the method to invoke when the Radio Button clicked
android:text Set text for the Radio Button
android:textSize Used to specify the text size for Radio Button's text
android:textStyle It is used to styling the text of the Radio Button. E.g. Bold, Italic
android:textColor Sets color for Radio Button's text
android:typeface Specifies the typeface like normal, sans, serif.

4. Radio Button Example

This is a simple Android Radio Button example in which we have taken some Radio Buttons. When the user clicks on the Radio Button, app will show the toast. Let’s get started.

Step 4.1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Step 4.2: Enable View Binding

In this example we are using Android Jetpack’s feature view binding.

Groovy
content_copy light_mode remove
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    ...
    ...

    buildFeatures {
        viewBinding = true
    }
    ...
    ...
}

dependencies {
    ...
    ...
    ...
}

Step 4.3: Add Radio Buttons to the XML Layout (UI)

Add some Android Radio Buttons to the xml layout from the palette.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:padding="10dp"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:text="Which is your favorite color:" />

    <!--Radio Group-->
    <RadioGroup
        android:id="@+id/colorRadioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!--Radio Button-->
        <RadioButton
            android:id="@+id/redRadioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#ff0000"
            android:buttonTint="#ff0000"
            android:text="Red" />

        <!--Radio Button-->
        <RadioButton
            android:id="@+id/greenRadioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#00ff00"
            android:buttonTint="#00ff00"
            android:text="Green" />

        <!--Radio Button-->
        <RadioButton
            android:id="@+id/blueRadioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#0000ff"
            android:buttonTint="#0000ff"
            android:text="Blue" />

        <!--Radio Button-->
        <RadioButton
            android:id="@+id/otherColorRadioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Other" />

    </RadioGroup>

    <Button
        android:layout_marginTop="15dp"
        android:id="@+id/submitButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="#7B1FA2"
        android:text="SUBMIT" />
</LinearLayout>

Step 4.4: Update Activity File

Open the Activity file and declare the onCheckedChanged event for all radio buttons. We have also taken a button. When the user clicks the button, the app will display a toast with the text of the selected radio button.

KotlinJava
content_copy light_mode remove
package com.androidchunk.helloradiobutton

import android.os.Bundle
import android.view.View
import android.widget.CompoundButton
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.androidchunk.helloradiobutton.databinding.ActivityMainBinding

internal class MainActivity : AppCompatActivity(), CompoundButton.OnCheckedChangeListener {
    //View binding
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //register check change listener for all radio buttons
        binding.redRadioButton.setOnCheckedChangeListener(this)
        binding.greenRadioButton.setOnCheckedChangeListener(this)
        binding.blueRadioButton.setOnCheckedChangeListener(this)
        binding.otherColorRadioButton.setOnCheckedChangeListener(this)

        binding.submitButton.setOnClickListener(View.OnClickListener {
            //get selected radio button from radiogroup
            val buttonId: Int = binding.colorRadioGroup.checkedRadioButtonId
            if (buttonId == View.NO_ID) {
                Toast.makeText(this@MainActivity, "Nothing selected", Toast.LENGTH_SHORT).show()
            } else {
                val selectedRadioButton = findViewById<RadioButton>(buttonId)
                Toast.makeText(this@MainActivity,"Your favorite color is: " + selectedRadioButton.text,Toast.LENGTH_SHORT).show()
            }
        })
    }

    override fun onCheckedChanged(compoundButton: CompoundButton, isChecked: Boolean) {
        if (compoundButton is RadioButton && isChecked) {
            Toast.makeText(this@MainActivity,compoundButton.getText().toString() + " selected",Toast.LENGTH_SHORT).show()
        }
    }
}
package com.androidchunk.helloradiobutton;

import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.androidchunk.helloradiobutton.databinding.ActivityMainBinding;

class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
    //View binding
    ActivityMainBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //register check change listener for all radio buttons
        binding.redRadioButton.setOnCheckedChangeListener(this);
        binding.greenRadioButton.setOnCheckedChangeListener(this);
        binding.blueRadioButton.setOnCheckedChangeListener(this);
        binding.otherColorRadioButton.setOnCheckedChangeListener(this);

        binding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //get selected radio button from radiogroup
                int buttonId = binding.colorRadioGroup.getCheckedRadioButtonId();
                if (buttonId == View.NO_ID) {
                    Toast.makeText(MainActivity.this, "Nothing selected", Toast.LENGTH_SHORT).show();
                } else {
                    RadioButton selectedRadioButton = findViewById(buttonId);
                    Toast.makeText(MainActivity.this, "Your favorite color is: "+selectedRadioButton.getText(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        if (compoundButton instanceof RadioButton && isChecked) {
            Toast.makeText(MainActivity.this, compoundButton.getText()+" selected", Toast.LENGTH_SHORT).show();
        }
    }
}

Boom..! That’s how easy it is. Happy coding!

Step 4.5: Output

Leave a Reply