Only one radio button selected at a time

若如初见. 提交于 2019-12-04 08:59:32

If they are in a radiogroup, only one can be selected at a time. If you want both to be able to be selected, remove them from the radiogroup.

As the top voted answer didn't work for me as for many others. I am sharing the method that i used and its working perfectly.

<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>

Setting the android:checkedButton="@+id/rb_female" worked for me in RadioGroup.

You should remove your onRadioButtonClick method and add OnCheckedChangeListener to your radiogroup. http://developer.android.com/reference/android/widget/RadioGroup.OnCheckedChangeListener.html

I guess by implementing your own click handler your are overwriting some functionality of the radiogroup.

Ajay Kumar Meher

Your requirement is not clear. Would you mind to make it simpler. I tried my best to understand your requirements and these are the findings given below :(.

A radio button can have text. So you don't have to add another TextView in your layout. Please remove them and add a simple android:text="blah.. blah.." to your radiobutton.

With my understanding you have two doubts.

How to customize RadioButtons with custom drawables??

Checkout the answer here.

How to deselect the previously selected radiobutton??

The truth is you don't have to do it manually as you are keeping those radiobuttons into a single radiogroup.

Hope this will help you.

Anth

To check/uncheck radio buttons not part of a RadioGroup, add a method in the android GUI designer under the RadioButton Properties 'onClick' (In this example radio1_onClick).

In your activity.xml under the xml for the RadioButton

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

In your activity_main.xml you would write the following method.

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 */
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!