Как установить только один 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.


person F_X    schedule 19.05.2016    source источник


Ответы (7)


Это не работает из-за 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>

Надеюсь это поможет. :)

person Janki Gadhiya    schedule 19.05.2016
comment
Вау, спасибо! это ответ, все кнопки могут быть выбраны один раз до н.э. в таблице :) Спасибо за помощь - person F_X; 19.05.2016
comment
Кстати, я использую TableRow, чтобы сделать переключатель в 2 строки, так как же сделать его 2rwos без tablerow? - person F_X; 19.05.2016

  <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
}
person Vishwesh Jainkuniya    schedule 19.05.2016
comment
Следуя вашему коду, но все радиокнопки по-прежнему можно выбрать за один раз, я использую фрагмент, кстати, - person F_X; 19.05.2016

Я столкнулся с той же проблемой и нашел, где я делал ошибки, и я описываю это ниже:

  1. Если вы используете RadioButtons в RadioGroup, тогда RadioButtons should be direct child of RadioGroup.

  2. Проверьте свое первое условие, и если оно было правильным, то give id to RatioButton и запустите проект, он автоматически решит вашу проблему.

person Vivek Thummar    schedule 25.06.2019

Я заметил, что одиночный выбор не работает без установки переключателей id.

             <RadioGroup
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/expenseRadio"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:text="@string/expense" />

                <RadioButton
                    android:id="@+id/incomeRadio"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/income" />
            </RadioGroup>
person Rasel    schedule 19.12.2019

Простой способ. onclick переключателя. сделайте код, как показано ниже.

public void clearRadioChecked() {
    rdopa.setChecked(false);
    rdopb.setChecked(false);
    rdopc.setChecked(false);
    rdopd.setChecked(false);
}

если вы хотите выбрать rdopa, то при нажатии rdopa сделайте, как показано ниже.

clearRadioChecked()
rdopa.setChecked(true);
person Vasant    schedule 19.05.2016
comment
Тогда нам лучше использовать флажки. Вы не используете RadioButton для ручной проверки и снятия отметки. Поведение по умолчанию: одно может быть отмечено сразу, другое будет автоматически снято. - person Janki Gadhiya; 19.05.2016
comment
@ janki gadhiya, если у вас есть группа переключателей и вы хотите повторно использовать их много раз, вам нужно реализовать описанный выше способ. В противном случае есть одна группа переключателей, тогда она работает нормально в соответствии с вашей концепцией. - person Vasant; 19.05.2016

Вы можете использовать атрибут 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>
person Levon Petrosyan    schedule 31.01.2019

Вы можете создать свою собственную RadioGroup, которая сможет найти все RadioButtons, вложенные в вашу группу, независимо от того, является ли она прямым потомком или нет. Ниже код моей 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));
            }
        }
    }
}

Есть идеи сделать код чище?

Я надеюсь, что это сработает для вас :)

person SuperSmartWorld    schedule 15.06.2019