Выбрана только одна радиокнопка за раз

У меня есть два переключателя в группе переключателей. У меня также есть 2 флажка android:button - когда переключатель не выбран, и checkbox_v, когда пользователь устанавливает флажок. Я также реализовал метод onRadioButtonClick, чтобы убедиться, что только один переключатель имеет drawable:checkbox, а другой имеет checkbox_v. Как я могу реализовать это на RadioClick? Есть идеи?

public void onRadioButtonClick(View v)
{
    RadioButton button = (RadioButton) v;
    boolean checkBox1Selected;
    boolean checkBox2Selected = false;

    Toast.makeText(MainActivity.this,
        button.getId()+ " was chosen."+R.id.wificheckBox,
        Toast.LENGTH_SHORT).show();

    if ( button.getId() ==R.id.wificheckBox) {
        // Toggle status of checkbox selection
        checkBox1Selected = radiowifiButton.isChecked();

        // Ensure that other checkboxes are not selected
        if (checkBox2Selected) {
            radiomobileButton.setChecked(false);
            checkBox2Selected = false;
        }
        else if (button.getId() ==R.id.wifimobilecheckBox) {
            // Toggle status of checkbox selection
            checkBox2Selected = radiomobileButton.isChecked();
            // Ensure that other checkboxes are not selected
            if (checkBox1Selected) {
                radiowifiButton.setChecked(false);
                checkBox1Selected = false;
            }
        }
    }

основной xml

<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true"
    android:layout_below="@+id/ll_1"
    android:layout_marginLeft="20dp">

<LinearLayout
    android:id="@+id/ll_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/ll_1"
    android:layout_marginLeft="20dp"
    android:orientation="horizontal" >

    <RadioButton
        android:id="@+id/wifimobilecheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/button_radio"
        android:checked="true"
        android:onClick="onRadioButtonClick" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/wificheckBox"
        android:layout_toRightOf="@+id/wificheckBox"
        android:paddingLeft="15dp"
        android:text="WiFi or mobile network"
        android:textColor="#333333"
        android:textSize="20dp" />
</LinearLayout>

<LinearLayout
    android:id="@+id/ll_3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/ll_2"
    android:paddingTop="20dp"
    android:layout_marginLeft="20dp"
    android:orientation="horizontal" >

    <RadioButton
        android:id="@+id/wificheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/button_radio"

        android:onClick="onRadioButtonClick" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/wificheckBox"
        android:layout_toRightOf="@+id/wificheckBox"
        android:paddingLeft="15dp"
        android:text="WiFi "
        android:textColor="#333333"
        android:textSize="20dp" />
</LinearLayout>

</RadioGroup>

Drawabe- button_radio

<item android:state_checked="true"android:state_pressed="false" android:drawable="@drawable/checkbox_v"/><item android:state_checked="false"android:state_pressed="false"'android:drawable="@drawable/checkbox"/>

person user182192    schedule 11.04.2012    source источник
comment
что ты пробовал? вставьте свой код сюда   -  person Sandip Armal Patil    schedule 11.04.2012


Ответы (5)


Если они находятся в радиогруппе, одновременно можно выбрать только одну. Если вы хотите, чтобы оба были выбраны, удалите их из радиогруппы.

person Bill Gary    schedule 11.04.2012
comment
Неправильно. Я настраиваю переключатель с помощью собственного drawable/checkbox и drawable/checkbox_v вместо стандартного. В настоящее время я могу выбрать обе кнопки radi, и обе они настраивают изображение drawable/checkbox_v - person user182192; 11.04.2012

Поскольку ответ с наибольшим количеством голосов не сработал для меня, как и для многих других. Я делюсь методом, который я использовал, и он отлично работает.

<RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checkedButton="@+id/rb_female"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/rb_female"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:layout_marginRight="10dp"
                android:button="@drawable/selector_radio_button"
                android:text="Female" />

            <RadioButton
                android:id="@+id/rb_male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:button="@drawable/selector_radio_button"
                android:text="Male" />
</RadioGroup>

Установка android:checkedButton="@+id/rb_female" сработала для меня в RadioGroup.

person Bilal Haider    schedule 13.12.2016

Вы должны удалить свой метод onRadioButtonClick и добавить OnCheckedChangeListener в свою радиогруппу. http://developer.android.com/reference/android/widget/RadioGroup.OnCheckedChangeListener.html

Я предполагаю, что, реализуя свой собственный обработчик кликов, вы перезаписываете некоторые функции радиогруппы.

person timoschloesser    schedule 11.04.2012

Ваше требование не ясно. Не могли бы вы сделать это проще. Я изо всех сил старался понять ваши требования, и вот выводы, приведенные ниже :(.

Радиокнопка может иметь текст. Таким образом, вам не нужно добавлять еще один TextView в макет. Пожалуйста, удалите их и добавьте простой android:text="blah.. blah.." к вашей радиокнопке.

Насколько я понимаю, у вас есть два сомнения.

Как настроить RadioButtons с помощью настраиваемых рисунков??

Проверьте ответ здесь.

Как отменить выбор ранее выбранного переключателя??

Правда в том, что вам не нужно делать это вручную, поскольку вы держите эти радиокнопки в одной радиогруппе.

Надеюсь, что это поможет вам.

person Ajay Kumar Meher    schedule 17.05.2013

Чтобы установить/снять отметку с переключателей, не являющихся частью RadioGroup, добавьте метод в конструктор графического интерфейса Android в свойствах RadioButton «onClick» (в этом примере radio1_onClick).

В вашем activity.xml под xml для RadioButton

RadioButton 
    [blah blah blah]
    android:id="@+id/radio1"
    android:onClick="radio1_onClick"

В вашем activity_main.xml вы должны написать следующий метод.

private void radio1_onClick(View v)
{
    CompoundButton b=(CompoundButton)findViewById(R.id.radio1);
    b.setChecked(true); /* light the button */

    //b.setChecked(false); /* unlight the button */
}
person Anth    schedule 29.06.2013