I'm creating a radio question here I want select only one button to be selected. But here both buttons are got selected. kindly give me the solutions.
private void radioButtonQuestion(String radioquest, JsonArray optionsArray) {
RadioButton radio;
RadioGroup radioGroup;
JsonArray dependenciesArray = (JsonArray) indQuestions.get("dependencies");
ArrayList<String> list = new ArrayList<>();
for(int a=0; a<optionsArray.size();a ) {
JsonObject optionsObject = (JsonObject) optionsArray.get(a);
JsonObject dependenciesObject = (JsonObject) dependenciesArray.get(a);
String option = optionsObject.get("value").getAsString();
list.add(option);
}
LinearLayout ll=new LinearLayout(context);
ll.setOrientation(LinearLayout.VERTICAL);
cardview = new CardView(context);
layoutparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutparams.setMargins(10,20,10,20);
cardview.setLayoutParams(layoutparams);
cardview.setRadius(30);
cardview.setPadding(10, 10, 10, 10);
cardview.setCardBackgroundColor(Color.WHITE);
cardview.setMaxCardElevation(20);
cardview.setMaxCardElevation(6);
textview = new TextView(context);
// textview.setLayoutParams(layoutparams);
textview.setText(radioquest);
textview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textview.setTextColor(Color.BLACK);
textview.setPadding(15, 25, 25, 15);
textview.setGravity(Gravity.NO_GRAVITY);
ll.addView(textview);
for(int i = 0; i< list.size();i ) {
radio = new RadioButton(context);
radioGroup = new RadioGroup(context);
radio.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
radio.setPadding(15, 15, 15, 15);
radio.setId(i);
radio.setText(list.get(i));
radioGroup.addView(radio);
ll.addView(radioGroup);
}
ll.setId(id);
cardview.addView(ll);
cardview.setId(id);
cardview.setTag("Radio " id);
id ;
relativeLayout.addView(cardview);
}
CodePudding user response:
Your code created a different group for each individual radio button, that's why each can be selected at the same time. Each group can have one selected radio button. Instead, you should create just one group, and add all the buttons to that group.
CodePudding user response:
Just place radioGroup before options like below
radioGroup = new RadioGroup(context);
for(int i = 0; i< list.size();i ) {
radio = new RadioButton(context);
radio.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
radio.setPadding(15, 15, 15, 15);
radio.setId(i);
radio.setText(list.get(i));
radioGroup.addView(radio);
ll.addView(radioGroup);
}