我在我的布局中添加一个RadioButton。单选按钮不会切换其状态
这是没有检查开始。当我点击它时,它会被检查(如模拟器所示)。但是当我再次点击它时,它不会再被取消选中?
<RadioButton android:checked="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/option1"/>
我在我的布局中添加一个RadioButton。单选按钮不会切换其状态
这是没有检查开始。当我点击它时,它会被检查(如模拟器所示)。但是当我再次点击它时,它不会再被取消选中?
<RadioButton android:checked="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/option1"/>
如果您只使用一个收音机盒进行检查和关闭,也许应该使用复选框或切换按钮。
http://developer.android.com/resources/tutorials/views/hello-formstuff.html
向下滚动,看到复选框和切换按钮。
使用无线电时,通常有多个无线电,并在它们之间进行选择。像简单,中等,很难。
我该如何在自己的控件中指定'android's checkboxStyle'? – michael 2010-07-26 21:42:44
这是一个概念性问题:单选按钮允许您在多个选项(由其他单选按钮表示)之间进行选择。通常,组中的一个单选按钮始终被检查,即使在初始状态下,如果您没有声明一个按钮为默认值,也不会检查任何按钮。这意味着一个按钮不允许切换其状态,除非其他单选按钮出现在同一组中 - 如果只有一个选项,则必须选择它。
如果您想要二进制切换,您将希望使用复选框。
如果你有超过1个单选按钮与再添加如下“RadioGroups”的工作:
<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical">
<RadioButton android:id="@+id/radio1" android:text="madras"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<RadioButton android:id="@+id/radio2" android:text="bombay"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RadioGroup>
看一看这个example,我相信这会令你的想法明确有关收音机按钮。
的解决方案是设置检查[真/假]如果你正在寻找一个单选按钮的外观复选框行为中间Java代码
ToggleButton t = (ToggleButton) findViewById(R.id.toggle_button);
t.setChecked(true);
// t.setChecked(false);
,你可以在XML风格传递给一个复选框。
<CheckBox android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/option1"
style="@android:style/Widget.DeviceDefault.Light.CompoundButton.RadioButton/>
这可以(用在RecyclerView单选按钮前)。在某些情况下非常有用,但因为用户希望单选按钮的行为以一定的方式,你应该小心。如果您允许用户进行多项选择,则应该使用正常复选框,如上面的注释中所述。
希望这有助于!
在搜索了很多关于SO后,我想出了一个不太好但体面的解决方法。
为每个RadioButton声明一个boolean
变量,用false
对其初始化,并在每次点击时更改变量和RadioButton的状态。
boolean isToggledRadio1 = false;
RadioButton radio1 = (RadioButton) findViewById(R.id.radiobutton1);
radio1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isToggledRadio1 = !isToggledRadio1; //Switch boolean value
RadioButton rb = (RadioButton)v;
rb.setChecked(isToggledRadio1);
}
});
我知道这是理想的使用复选框,但如果有人需要的单选按钮,然后他们需要的单选按钮。
这不是一个最佳的解决方案,因为它会在每次用户点击该按钮时基本上切换按钮两次(一个是默认行为,第二次就是你的onclick函数中),所以如果你”重新使用OnCheckedChangeListener
,您可能会收到两次同样的点击。
还有另一种解决方法,即将复选框中的android:button
更改为带有xml模板的另一个drawable,但它稍微复杂一些,需要至少2个以上的文件才能存在。
它适用于我。谢谢 – Vrajesh 2018-03-05 09:24:53
但是,这是一个单选按钮*应该*的工作方式。 – 2010-07-26 19:42:49