我在对话框中有两个复选框。我想为这些复选框设置单个检查。这意味着如果我选中了复选框1,复选框2将被取消选中。当我检查复选框2时类似。如果选中复选框1,则check_value
变量设置为true,并且在复选框2选中时为false。如何在Android对话框中选中复选框?
这是我的代码,但我的预期
@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文件,它无法实现。默认情况下,复选框1为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>
为什么复选框而不是单选按钮?他们是为此目的而生的 –
你能用单选按钮来回答我的问题吗?请注意,我将它们放在对话框中 – user3051460
对不起,现在我没有编译器。只需看看[这篇文章如何在构建器中使用自定义布局](http://stackoverflow.com/questions/22655599/alertdialog-builder-with-custom-layout-and-edittext-cannot-access-view)你也可以参考[这个链接也](http://stackoverflow.com/questions/27785167/radio-buttons-in-android-studio)如何使用单选按钮。希望这有助于 –