Android Radio Button Example

The android.widget.RadioButton class is used to implement the radio button UI component in android applications. The 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.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/sfV14kA0vm4

  1. This example includes the following core files: activity_radio_button.xml, strings.xml, RadioButtonActivity.java, AndroidManifest.xml.
    ./
    ├── app
    │   ├── build.gradle
    │   ├── proguard-rules.pro
    │   └── src
    │       ├── main
    │       │   ├── AndroidManifest.xml
    │       │   ├── java
    │       │   │   └── com
    │       │   │       └── dev2qa
    │       │   │           └── example
    │       │   │               ├── RadioButtonActivity.java
    │       │   ├── res
    │       │   │   ├── layout
    │       │   │   │   ├── activity_radio_button.xml
    │       │   │   ├── values
    │       │   │   │   ├── strings.xml
    

2. activity_radio_button.xml

  1. This layout XML file is saved in the app/res/layout folder, it includes one RadioGroup component. The RadioGroup contains two RadioButton components.
  2. Use RadioGroup’s android:checkedButton attribute to specify the default selected radio button.
  3. The RadioButton‘s text values are all retrieved from the file 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

  1. This file is a resource file that contains all strings used in the android application. It is saved in the app/res/values folder.
  2. Each string resource in this file has a name attribute.
  3. The string resource can be used in the layout XML file like the below format. android:text=”@string/select_role_label”.
  4. To get resource string value in java source code, you can write code like below.
    String promptMessage = getResources().getString(R.string.select_role_prompt)
  5. Use \n to start a new line in a 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

  1. This is the activity java class, there are two listeners in this file, one is used to listen to radio button check or uncheck event ( OnCheckedChangeListener ), the other is used to listen button click event ( OnClickListener ). Please see code comments for more detailed explanations.
    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

  1. 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>
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x