Как установить только один RadioButton Может быть выбран в то время в RadioGroup
Я создал радиокнопку в радиогруппе, но когда я пытаюсь запустить приложения, все радиокнопки могут быть выбраны все время и как можно установить только одну радиобавку, можно выбрать за один раз?
Я использую Фрагмент
RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.RGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
if(checkedId == R.id.Abdominal) {
Toast.makeText(getActivity().getApplicationContext(), "choice: A",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Arm) {
Toast.makeText(getActivity().getApplicationContext(), "choice: B",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Back){
Toast.makeText(getActivity().getApplicationContext(), "choice: C",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Chest){
Toast.makeText(getActivity().getApplicationContext(), "choice: D",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Leg){
Toast.makeText(getActivity().getApplicationContext(), "choice: E",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Shoulder){
Toast.makeText(getActivity().getApplicationContext(), "choice: F",
Toast.LENGTH_SHORT).show();
}
}
});
здесь мой xml-код для RG и RB
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/RGroup">
<TableRow android:weightSum="1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Abdominal"
android:id="@+id/Abdominal"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Arm"
android:id="@+id/Arm"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="@+id/Back" />
</TableRow>
<TableRow>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chest"
android:id="@+id/Chest"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leg"
android:id="@+id/Leg"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shoulder"
android:id="@+id/Shoulder"/>
</TableRow>
</RadioGroup>
EDITED 1: Ответ:
Если вы не хотите, чтобы переключатель был выбран за один раз, поэтому не используйте Tablerow
Ответы
Ответ 1
Он не работает из-за TableRow внутри RadioGroup. Все RadioButtons не группируются из-за TableRow между ними.
RadioButton должен быть прямым дочерним элементом RadioGroup, в противном случае группировка не работает.
Просто измените свой код, как будто он будет работать:
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/RGroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Abdominal"
android:id="@+id/Abdominal"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Arm"
android:id="@+id/Arm"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="@+id/Back" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chest"
android:id="@+id/Chest"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leg"
android:id="@+id/Leg"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shoulder"
android:id="@+id/Shoulder"/>
</RadioGroup>
Надеюсь, это поможет.:)
Ответ 2
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:id="@+id/radioGroup">
<RadioButton
android:layout_width="0dp"
android:layout_weight="50"
android:layout_height="wrap_content"
android:text="Debit"
android:id="@+id/rDebit"
android:checked="false"
/>
<RadioButton
android:layout_width="0dp"
android:layout_weight="50"
android:layout_height="wrap_content"
android:text="Credit"
android:id="@+id/rCredit"
android:checked="false" />
</RadioGroup>
И в java файле
RadioGroup radioGroup;
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
И когда что-то делать
if (radioGroup.getCheckedRadioButtonId() == R.id.rCredit)
{
// do something
}
Ответ 3
Простой способ. onclick переключателя. выполните код, как показано ниже.
public void clearRadioChecked() {
rdopa.setChecked(false);
rdopb.setChecked(false);
rdopc.setChecked(false);
rdopd.setChecked(false);
}
если вы выбрали rdopa, а затем нажмите кнопку rdopa, как показано ниже.
clearRadioChecked()
rdopa.setChecked(true);
Ответ 4
Вы можете использовать атрибут android:checkedButton
в RadioGroup, предоставляя id
RadioButton, который вы хотите проверить вначале, и выбор другого RadioButton очистит предыдущий выбор.
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkedButton="@+id/rbNo"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="50dp"
android:text="Yes" />
<RadioButton
android:id="@+id/rbNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No" />
</RadioGroup>
Ответ 5
Вы можете создать свою собственную RadioGroup, которая сможет найти все RadioButton, которые вложены в вашу группу, независимо от того, является ли ребенок прямым или нет. Ниже приведен код моей NestedRadioGroup. Использование этого вместо вашей RadioGroup в вашем XML файле должно помочь.
public class NestedRadioGroup extends LinearLayout {
private SparseArray<RadioButton> radioButtons;
private int checkedId;
public NestedRadioGroup(Context context) {
this(context, null);
}
public NestedRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);
radioButtons = new SparseArray<>();
checkedId = -1;
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
super.addView(child, index, params);
findRadioButtons(child);
}
private void findRadioButtons(View child) {
if (child instanceof RadioButton) {
RadioButton newButton = (RadioButton) child;
newButton.setId(radioButtons.size());
newButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
if (checkedId != -1) {
radioButtons.get(checkedId).setChecked(false);
}
radioButtons.get(buttonView.getId()).setChecked(true);
checkedId = buttonView.getId();
}
});
radioButtons.put(newButton.getId(), newButton);
} else if (child instanceof ViewGroup) {
ViewGroup group = (ViewGroup) child;
for (int i = 0; i < group.getChildCount(); i++) {
this.findRadioButtons(group.getChildAt(i));
}
}
}
}
Есть идеи, чтобы сделать код чище?
Я надеюсь, что у вас получится :)
Ответ 6
Я столкнулся с той же самой проблемой прямо сейчас и нашел, где я делал ошибки, и я описываю это ниже:
1) Если вы используете RadioButtons в RadioGroup, то RadioButtons должен быть прямым потомком RadioGroup.
2) Я проверил свое первое условие, и оно было правильным, но все-таки все переключатели выбираются, и когда он дает идентификаторы и запускает проект, он автоматически решает мою проблему.
Я надеюсь, что так.. мой ответ поможет вам!