无法在自定义AlertDialog.Builder上调用dismiss()

时间:2017-03-01 18:05:38

标签: java android android-alertdialog dismiss

我已创建此自定义AlertDialog.Builder

问题是我想在onClick

mPositiveBTN中将其解雇

dismiss()cancel()未定义!怎么做?

就是这样:

public class SendSmsDialog extends AlertDialog.Builder {

    private TextView mMessageTV;
    private Button mPositiveBTN;

    private EditText mobileNumberET;

    private Context mContext;

    public SendSmsDialog(@NonNull Context context, String title, String message) {
        super(context);
        mContext = context;

        LayoutInflater inflater = ((MainActivity)context).getLayoutInflater();
        View dialoglayout = inflater.inflate(R.layout.send_sms_dialog, null);
        this.setView(dialoglayout);

        bindViews(dialoglayout);
        setListeners();


        this.setTitle(title);
        mMessageTV.setText(message);
    }

    private void setListeners() {
        mPositiveBTN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mobileNumberET.setEnabled(true);
                mobileNumberET.requestFocus();

                if (UtilitiesMethods.checkEnteredPhone(mobileNumberET.getText().toString())) {
                    ((MainActivity)mContext).doSendSMS(mobileNumberET.getText().toString());
                } else {
                    SendSmsDialog.this.dismiss(); //not defined
                    mobileNumberET.setError("Please enter a correct mobile number");
                }
            }
        });
    }

    private void bindViews(View dialoglayout) {
        mMessageTV = (TextView) dialoglayout.findViewById(R.id.msg_tv);
        mPositiveBTN = (Button) dialoglayout.findViewById(R.id.proceed_btn);
        mobileNumberET = (EditText) dialoglayout.findViewById(R.id.mobile_num);
    }
}

2 个答案:

答案 0 :(得分:2)

我总是像这样使用AlertDialog.Builder:

private AlertDialog.Builder builder;
private AlertDialog dialog;
.
.
.
.
    builder = new AlertDialog.Builder(this);
    builder.setTitle("Add your account");
    builder.setView(rootView);

并显示我使用的对话框:

dialog = builder.show();

show方法返回一个AlertDialog.so我可以通过以下方式解除它:

 dialog.dismiss();

答案 1 :(得分:0)

构建器本身不是对话框,这意味着您无法在构建器上完全调用dismiss。

您可能应该扩展AlertDialog而不是AlertDialog.Builder。