package com.example.
radiobutton;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize radio group and button
RadioGroup radioGroup = findViewById(R.id.radioGroup);
Button buttonSubmit = findViewById(R.id.buttonSubmit);
// Set onClickListener for the button
buttonSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the selected radio button id
int selectedRadioButtonId =
radioGroup.getCheckedRadioButtonId();
// Check which radio button is selected
String selectedOption = "";
switch (selectedRadioButtonId) {
case R.id.radioButtonOption1:
selectedOption = "Option 1";
break;
case R.id.radioButtonOption2:
selectedOption = "Option 2";
break;
case R.id.radioButtonOption3:
selectedOption = "Option 3";
break;
default:
selectedOption = "None selected";
}
// Display a toast message with the selected option
Toast.makeText(getApplicationContext(), "Selected option: " +
selectedOption, Toast.LENGTH_SHORT).show();
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radioButtonOption1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />
<RadioButton
android:id="@+id/radioButtonOption2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />
<RadioButton
android:id="@+id/radioButtonOption3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3" />
</RadioGroup>
<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>