I want to use Radio Group with buttons on Android studio
I'm developing an Android application where I need to capture user input using RadioGroup within an AlertDialog. Below is the code snippet I'm using:
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class MainActivity extends AppCompatActivity {
Button bt;
RadioGroup g1;
RadioGroup g2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = findViewById(R.id.button);
g1 = findViewById(R.id.radioGroup);
g2 = findViewById(R.id.radioGroup2);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle("Alert");
alertDialogBuilder.setMessage("Click Yes to Submit").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int ans1 = g1.getCheckedRadioButtonId();
int ans2 = g2.getCheckedRadioButtonId();
String selectedOptionQ1 = "";
String selectedOptionQ2 = "";
if(ans1 != -1) {
View selectedRadioButtonViewQ1 = g1.findViewById(ans1);
if(selectedRadioButtonViewQ1 != null && selectedRadioButtonViewQ1 instanceof RadioButton) {
selectedOptionQ1 = ((RadioButton) selectedRadioButtonViewQ1).getText().toString();
}
}
if(ans2 != -1) {
View selectedRadioButtonViewQ2 = g2.findViewById(ans2);
if(selectedRadioButtonViewQ2 != null && selectedRadioButtonViewQ2 instanceof RadioButton) {
selectedOptionQ2 = ((RadioButton) selectedRadioButtonViewQ2).getText().toString();
}
}
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
intent.putExtra("selectedOptionQ1", selectedOptionQ1);
intent.putExtra("selectedOptionQ2", selectedOptionQ2);
startActivity(intent);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
}
I have an AlertDialog in this code with two RadioGroup instances (g1 and g2) containing multiple RadioButton options each. Upon clicking the "Yes" button in the dialog, I want to capture the selected options from both RadioGroups and pass them to another activity using intent.
The code seems to work fine, but I'm wondering if there's a more efficient or concise way to handle the selection of radio buttons within a RadioGroup in Android. Are there any best practices or alternative methods I should consider for achieving this functionality? Any insights or suggestions would be greatly appreciated!
Main Activity 2