Android Radio Button Example

android.widget.RadioButton class is used to implement radio button UI component in android application. android.widget.RadioGroup class is used to group multiple android.widget.RadioButton objects into one group. Then you can get user selected radio button and it’s values.

1. Example Screen Effect And Project File Structure.

First let us look at the screen effect of this example.

android radio button example

This example includes following core files : activity_radio_button.xml, strings.xml, RadioButtonActivity.java, AndroidManifest.xml.

android radio button example project file structure

2. activity_radio_button.xml

This layout xml file is saved in app / res / layout folder, it include one RadioGroup component. The RadioGroup contains two RadioButton components.

  1. Use RadioGroup’s android:checkedButton attribute to specify the default selected radio button.
  2. The RadioButton’s text value are all retrieved from app / res / values / strings.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.dev2qa.example.RadioButtonActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textViewSelectRole"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/select_role_label" />

            <RadioGroup
                android:id="@+id/roleRadioGroup"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="9"
                android:checkedButton="@+id/roleTeacher">

                <RadioButton
                    android:id="@+id/roleTeacher"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/teacher_role" />

                <RadioButton
                    android:id="@+id/roleStudent"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/student_role" />

            </RadioGroup>
        </LinearLayout>

        <Button
            android:id="@+id/showRadioBoxValue"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Show Selection" />

    </LinearLayout>
</android.support.constraint.ConstraintLayout>

3. strings.xml

This file is resource file which contains all strings used in android application. It is save at app / res / values folder.

  1. Each string resource in this file has a name attribute.
  2. The string resource can be used in layout xml file like below format. android:text=”@string/select_role_label”.
  3. To get resource string value in java source code, you can write code like below.
    String promptMessage = getResources().getString(R.string.select_role_prompt)
  4. Use \n to start a new line in string value.
<resources>
    <string name="select_role_label">Select Your \nRole : </string>
    <string name="teacher_role">Teacher</string>
    <string name="student_role">Student</string>
    <string name="select_role_prompt">Your selected role is : </string>
</resources>

4. RadioButtonActivity.java

This is the activity java class, there are two listeners in this file, one is used to listen radio button check or uncheck event ( OnCheckedChangeListener ) , the other is used to listen button click event ( OnClickListener ). Please see code comments for more detail explanation.

package com.dev2qa.example;

import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class RadioButtonActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Use activity_radio_button layout.
        setContentView(R.layout.activity_radio_button);

        // This listener is used to listen user check or uncheck teacher radio button.
        RadioButton teacherRadioButton = (RadioButton)findViewById(R.id.roleTeacher);
        teacherRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                String showMsg = "";
                if(checked)
                {
                    // If user check teacher radio button.
                    showMsg = "You checked Teacher role.";
                }else
                {
                    // If user uncheck teacher radio button.
                    showMsg = "You unchecked Teacher role.";
                }

                // Create an AlertDialog object.
                AlertDialog alertDialog = new AlertDialog.Builder(RadioButtonActivity.this).create();

                alertDialog.setMessage(showMsg);

                // Show the alert dialog.
                alertDialog.show();
            }
        });

        // Get show radio select item button.
        Button showRadioValueBtn = (Button) this.findViewById(R.id.showRadioBoxValue);

        // Register OnClickListener object to showRadioValueBtn button.
        showRadioValueBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Get RadioGroup by id.
                RadioGroup roleGroup = (RadioGroup) findViewById(R.id.roleRadioGroup);

                // Get user selected radio button id.
                int checkedRadioBtnId = roleGroup.getCheckedRadioButtonId();

                // Get user selected RadioButton object by id.
                RadioButton radioButton = (RadioButton) findViewById(checkedRadioBtnId);

                // Get the RadioButton text.
                String selectText = (String) radioButton.getText();

                // Create an AlertDialog object.
                AlertDialog alertDialog = new AlertDialog.Builder(RadioButtonActivity.this).create();

                // Get string resource and construct prompt message.
                String promptMessage = getResources().getString(R.string.select_role_prompt) + selectText;

                // Set prompt message.
                alertDialog.setMessage(promptMessage);

                // Show the alert dialog.
                alertDialog.show();
            }
        });
    }
}

5. AndroidManifest.xml

<activity android:name=".RadioButtonActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
(Visited 1,608 times, 5 visits today)
READ :   Android AutoCompleteTextView Example

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.