Advertisement




Android RadioGroup with Example

Advertisement

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

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

Advertisement

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

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

Advertisement

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

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

Advertisement
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 radio group 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>
Advertisement

Guides


Leave a Reply

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