What is Radio Group View in Android?
RadioGroup is a widget in android which is used to handle multiple radio buttons within the android application. We can add multiple radio buttons to our RadioGroup. We have seen how to use radio buttons in android. In this article, we will take a look at How to implement Radio Group in the android application.
I want logic to show in a string “Y” for Yes selection or “N” for No selection in the below code=int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { Toast.makeText(context, “No answer has been selected”, Toast.LENGTH_SHORT) .show(); } else { RadioButton radioButton = (RadioButton) radioGroup.findViewById(selectedId); Toast.makeText(context, radioButton.getText(), Toast.LENGTH_SHORT).show(); }
Solutions:
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(context,
“No answer has been selected”,
Toast.LENGTH_SHORT)
.show();
} else {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(selectedId);
String selectedText = radioButton.getText().toString();String result;
if (selectedText.equalsIgnoreCase(“Yes”)) {
result = “Y”;
} else if (selectedText.equalsIgnoreCase(“No”)) {
result = “N”;
} else {
result = “Invalid Selection”; // Handle unexpected cases
}Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
}
Explanation:
selectedId
: Checks if a radio button is selected usinggetCheckedRadioButtonId()
. If-1
, no button is selected.- Retrieve Button Text: The text of the selected button is retrieved using
radioButton.getText().toString()
. - Condition Check:
Post a Comment
0Comments