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.
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]
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.
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.