【发布时间】:2017-04-06 04:49:42
【问题描述】:
我在对话框中有两个复选框。我想为这些复选框设置单项检查。这意味着如果我选中了复选框 1,则复选框 2 将被取消选中。当我选中复选框 2 时类似。check_value 变量在选中复选框 1 时设置为 true,在选中复选框 2 时设置为 false。
这是我的代码,但它无法达到我的预期
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_dialogView, null);
boolean check_value=false;
checkbox1 = (CheckBox) dialogView.findViewById(R.id.checkbox1);
checkbox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkbox2.setChecked(false);
checkbox1.setChecked(true);
check_value=true;
}
});
checkbox2 = (CheckBox) dialogView.findViewById(R.id.checkbox2);
checkbox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkbox2.setChecked(true);
checkbox1.setChecked(false);
check_value=false;
}
});
}
这是我的 xml 文件。 checkbox1 默认为 true
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="@+id/list"
android:layout_centerInParent="true">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkbox1"
android:checked="true"
android:layout_marginLeft="2dp"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkbox2"
android:checked="false"
android:layout_marginLeft="2dp" />
</LinearLayout>
【问题讨论】:
-
为什么选择复选框而不是单选按钮?他们为此而生
-
你能用单选按钮回答我的问题吗?请注意,我将它们放在对话框中
-
对不起,现在我没有编译器。只需看看This post on how to use custom layouts in builders,您也可以参考this link also 了解如何使用单选按钮。希望这会有所帮助
标签: android checkbox android-widget