AlertDialog - 当用户点击"确定"时如何运行检查

ste*_*eve 4 android android-alertdialog

对于自定义AlertDialog,我可以覆盖肯定按钮以不关闭对话框吗?相反,我想运行一些编辑检查,并在检查失败时保持对话框打开.

protected Dialog onCreateDialog(int id) {
  Dialog alertDialog = null;
  builder = new AlertDialog.Builder(this);
  switch(id) {
    case LOGIN_USERID_BLANK:
      builder.setMessage((String)getString(R.string.username_not_blank));
      builder.setPositiveButton((String)getString(R.string.ok), new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
      // Can I do something here so that the dialog does not close?
}
});
Run Code Online (Sandbox Code Playgroud)

打破;

小智 6

在Google更改Dialog API之前,这是一种解决方法:

LayoutInflater factory = LayoutInflater.from(this);
final View view = factory.inflate(R.layout.yoMamma, null);
final Dialog dlg = new AlertDialog.Builder(this)
    .setTitle(R.string.yoTitle)
    .setView(view)
    .setPositiveButton(R.string.dlgOK, new DialogInterface.OnClickListener() {
      @Override public void onClick(DialogInterface dialog, int which) {
        // This won't be called.
      }})
    .create();
dlg.show();
View button = ((AlertDialog)dlg).getButton(DialogInterface.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
  @Override public void onClick(View v) {
    // This WILL be called.
    // Remove the following if you don't want the dialog to dismiss
    dlg.dismiss();
  }});
Run Code Online (Sandbox Code Playgroud)