RadioGroup

Radio Buttons will allow the users to select the one option from the group. If the user selects one radio buttons then it will uncheck previously checked radio button is selected within the same group.

For example:  If you have made two radio button for Gender, without RadioGroup then the user can select both the gender as there is not RadioGroup.

The solution is, we will use RadioGroup if a user selects one option it will unchecked other options.

Must Read: Google Map Tutorial in Android Studio [Step by Step]

In the MainActivity.java we are going to check through setOnCheckedChangeListener which Radio button is check.

Whichever the RadioButton is checked in a group the toast message will pop up.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    RadioGroup radioGroup;


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

        radioGroup = findViewById(R.id.radioGroup);


        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radioButton:
                        Toast.makeText(getApplicationContext(), "First Radio Is Selected",
                                Toast.LENGTH_LONG).show();
                        break;


                    case R.id.radioButton2:
                        Toast.makeText(getApplicationContext(), "Second Radio Is Selected",
                                Toast.LENGTH_LONG).show();
                        break;

                }
            }
        });

    }

}

In the main_activity.xml we will put the radiogroup first then we will put the radio button.

<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="202dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <RadioButton
        android:id="@+id/radioButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Text 1"
        android:textSize="24sp" />

    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Text 2"
        android:textSize="24sp" />
</RadioGroup>