0

我有一个带有 3 个单选按钮的 RadioGroup,比如 A、B 和 C,当我单击 A 时,它会弹出一个对话框,并使用 android 对话框的 setSingleChoiceItems,它会显示另外 4 个选项。问题是,如果我在此对话框上单击取消,现在仍在检查 A。我如何确保如果用户按下取消,A 保持未选中状态?我尝试了以下方法:

 CustomizedDialogFragment testDiag = new CustomizedDialogFragment();
           testDiag.show(getFragmentManager(), "Diag");
           if (testDiag.userChecked()){
               radioGroup.check(0);
           } else {
               radioGroup.clearCheck();
           }

    public static class CustomizedDialogFragment extends DialogFragment {
    private boolean checked = false;
    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setSingleChoiceItems(R.array.test_values, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0: break;
                            case 1: break;
                            case 2: break;
                            case 3: break;
                        }
                    }
                })

                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        checked = true;
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        checked = false;
                    }
                        });
        return builder.create();
    }

    public boolean userChecked(){
        return checked;
    }

}

但是,这不起作用。非常感谢任何类型的帮助。

4

1 回答 1

0

编辑:添加静态方法来创建片段的实例

private RadioGroup mGroup;

public static CustomizedDialogFragment create(RadioGroup group){
    CustomizedDialogFragment instance = new CustomizedDialogFragment(group);
    return instance;
}

protected CustomizedDialogFragment (RadioGroup group){
    mGroup = group;
}

将否定按钮单击更改为:

setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        //Clear RadioGroup selection
                        mGroup.check(-1);
                    }
                        });
于 2015-06-07T15:32:26.773 回答