Android:RadioButtons中的RadioButtons

时间:2015-06-07 15:09:40

标签: android android-dialogfragment android-dialog android-radiogroup android-radiobutton

我有一个带有3个radiobuttons的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;
    }

}

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

1 个答案:

答案 0 :(得分: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);
                    }
                        });