使用按钮关闭对话框按钮

时间:2018-02-01 22:15:47

标签: android android-studio

我有一个对话框,允许用户选择男性或女性。我可以通过单击关闭它来关闭它,但需要知道在单击mConfirm按钮时如何关闭它。

    public String getRadioValue() {
        final String[] mRadioString = {"Male"};

        final AlertDialog.Builder mBuilder = new AlertDialog.Builder(ProfileActivity.this);
        View mView = getLayoutInflater().inflate(R.layout.dialog_input, null);
        mBuilder.setCancelable(true);
        final RadioButton mMaleRadio = (RadioButton) mView.findViewById(R.id.radMale);
        final RadioButton mFemaleRadio = (RadioButton) mView.findViewById(R.id.radFemale);
        final RadioGroup mRadioGroup = (RadioGroup) mView.findViewById(R.id.radioGroup);
        Button mConfirm = (Button) mView.findViewById(R.id.btnConfirm);

        mConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mMaleRadio.isChecked()) {
                    mRadioString[0] = "Male";
                } else {
                    mRadioString[0] = "Female";
                }
                
            }
        });

        mBuilder.setView(mView);
        AlertDialog dialog = mBuilder.create();
        dialog.show();

        return mRadioString[0];
    }

1 个答案:

答案 0 :(得分:0)

ClickListener

中致电dialog.dismiss()
    final String[] mRadioString = {"Male"};

    final AlertDialog.Builder mBuilder = new AlertDialog.Builder(ProfileActivity.this);
    View mView = getLayoutInflater().inflate(R.layout.dialog_input, null);
    mBuilder.setCancelable(true);
    final RadioButton mMaleRadio = (RadioButton) mView.findViewById(R.id.radMale);
    final RadioButton mFemaleRadio = (RadioButton) mView.findViewById(R.id.radFemale);
    final RadioGroup mRadioGroup = (RadioGroup) mView.findViewById(R.id.radioGroup);
    Button mConfirm = (Button) mView.findViewById(R.id.btnConfirm);


    mBuilder.setView(mView);
    final AlertDialog dialog = mBuilder.create();

    mConfirm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mMaleRadio.isChecked()) {
                mRadioString[0] = "Male";
            } else {
                mRadioString[0] = "Female";
            }
            dialog.dismiss();                
        }
    });

    dialog.show();