我在對話框中有兩個複選框。我想爲這些複選框設置單個檢查。這意味着如果我選中了複選框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)如何使用單選按鈕。希望這有助於 –