• Meghan Gill

MaterialRadioButton with RadioGroup Example Tutorial


Facebook's public posts settings with radio buttons
Facebook's public post settings with radio buttons

A radio button is a two-states button that can be either checked or unchecked and a type of #selectioncontrol.


When the radio button is unchecked, the user can press or click it to check it. However, contrary to a #CheckBox, a radio button cannot be unchecked by the user once checked.



Radio Button Usage


Radio buttons are normally used when selecting options where you can only make 1 choice.


We use radio buttons in a RadioGroup. The class android.widget.RadioGroup is used to create a multiple-exclusion scope for a set of radio buttons. So, when several radio buttons live inside a radio group, checking one radio button unchecks all the others.


Important RadioGroup Methods


To identify in code, the user's radio button choice we need the method getCheckedRadioButtonId(). This is a default method of the radio group class. The radio button selection is identified by the unique id of the radio button as defined in the XML layout file.


Initially, all of the radio buttons are unchecked. While it is not possible to uncheck a particular radio button, the radio group can be cleared to remove the checked state by using the method clearCheck().



Attributes


MaterialRadioButton has several attributes that you can add in the XML:


android:text

android:textColor android:textSize android:textAppearance android:textStyle

padding


background Add drawables to the top, bottom, left or right of the text of the SwitchMaterial. The example here adds a drawable below the text. Feel free to experiment with positioning yourself.

MaterialRadioButton Example App



Step 1: Create a new Android Studio project with an Empty Activity. Name the project MaterialRadioButton Example.

The Save location should be a place that makes sense on your computer. If you click on the open folder you can choose a location.

Choose Java. Pick a minimum SDK of API 21: Android 5.0 (Lollipop). You do not need any legacy android support libraries.



Add the Widgets


Step 2: Use the code below to add a TextView, a RadioGroup, four MaterialRadioButtons and one MaterialButton.




Find your widgets in code


Step 3: Make sure all of your widgets have an id in the XML so that you can connect your UI to your code. For example, I added the id btnSubmit to the MaterialButton.


Declare a variable for the MaterialButton and the RadioGroup and use findViewByID to connect the variables to the UI elements.




Set a Listener


Step 4: Set an setOnClickListener() to the MaterialButton so that when the user presses it they receive a toast showing their language selection.


As a parameter type new then control + space to enable the interface. An onClick() method will automatically be generated to override.



btnSubmit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     }
});


Return the user's Language choice with a toast


Step 5: Inside the onClick() method create a variable of type int to hold the resource ID of the selected button. Name it selectedBtnId. Use the default method getCheckedRadioButtonId() to return the ID of the selected radio button.


int selectedBtnId = radioGroup.getCheckedRadioButtonId();

Step 6: By default getCheckedRadioButtonId() returns -1 if no radio button in the radio group has been selected. To safely account for the lack of a choice and to display a message to the user, we will create an if/else conditional with toasts.



@Override
public void onClick(View v) {
    int selectedBtnId = radioGroup.getCheckedRadioButtonId();

    if (selectedBtnId == -1) {
        Toast.makeText(MainActivity.this,
                "Nothing selected",
                Toast.LENGTH_SHORT).show();
    }
    else{
        MaterialRadioButton selectedRadioBtn = 
                findViewById(selectedBtnId); 
        Toast.makeText(MainActivity.this,
                "Choice selected: " + selectedRadioBtn.getText(),
                Toast.LENGTH_SHORT).show();
    } 

In the else part of the conditional create a variable of type MaterialRadioButton that can hold a reference to the user's selected radio button. Name it selectedRadioBtn. Create a toast to display the user's choice.


Now what?


Learn more about UI by checking out more #selectioncontrols such as the #checkbox or #SwitchMaterial.


Source code for activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity"
    android:layout_margin="24dp">

    <TextView
        android:id="@+id/tVLanguageSettings"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Language Settings"
        app:layout_constraintTop_toTopOf="parent"  android:textAppearance="@style/TextAppearance.AppCompat.Headline"/>

    <RadioGroup
        android:id="@+id/radioGroupLanguages"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
      app:layout_constraintTop_toBottomOf="@id/tVLanguageSettings">
        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/radioBtnEnglish"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="English"/>
        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/radioBtnSpanish"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Spanish"/>
        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/radioBtnMandarin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Mandarin"/>
        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/radioBtnRussian"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Russian"/>

    </RadioGroup>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnSubmit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SUBMIT"
    app:layout_constraintTop_toBottomOf="@id/radioGroupLanguages"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java:

package io.meghandev.materialradiobuttonexample;

import androidx.appcompat.app.AppCompatActivity;

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

import com.google.android.material.button.MaterialButton;
import com.google.android.material.radiobutton.MaterialRadioButton;

public class MainActivity extends AppCompatActivity {
    MaterialButton btnSubmit;
    RadioGroup radioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnSubmit = findViewById(R.id.btnSubmit);
        radioGroup = findViewById(R.id.radioGroupLanguages);

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedBtnId = 
                    radioGroup.getCheckedRadioButtonId();

                if (selectedBtnId == -1) {
                    Toast.makeText(MainActivity.this,
                            "Nothing selected",
                            Toast.LENGTH_SHORT).show();
                }
                else{
                    MaterialRadioButton selectedRadioBtn = 
                                findViewById(selectedBtnId);
                    Toast.makeText(MainActivity.this,
                            "Choice selected: " + 
                            selectedRadioBtn.getText(),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}











165 views0 comments

Recent Posts

See All