系统AlertDialog的点击确定dialog不消失

来源:互联网 发布:sql when case男 编辑:程序博客网 时间:2024/05/07 03:19

我们会用到android自带的alertDialog,非常简单,但是,弄完之后会发现,点击确定和取消,都对dialog进行了dismiss。

我们有时候需要对dialog点击确定进行判断,满足条件取消,不满足条件则不进行取消。

实现如下,新建一个ButtonHandler:

import android.content.DialogInterface;import android.os.Handler;import android.os.Message;import java.lang.ref.WeakReference;/** * Created by Administrator on 2016/9/27 0027. */public class ButtonHandler extends Handler {    private WeakReference<DialogInterface> mDialog;    public ButtonHandler(DialogInterface dialog) {        mDialog = new WeakReference<DialogInterface>(dialog);    }    @Override    public void handleMessage(Message msg) {        switch (msg.what) {            case DialogInterface.BUTTON_POSITIVE:            case DialogInterface.BUTTON_NEGATIVE:            case DialogInterface.BUTTON_NEUTRAL:                ((DialogInterface.OnClickListener) msg.obj).onClick(mDialog                        .get(), msg.what);                break;        }    }}
然后在我们弹出dialog的地方进行如下代码:

final EditText editText = new EditText(this);AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("请输入名称")        .setView(editText)        .setPositiveButton("确定", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                if (editText.getText().toString().length() == 0) {                    Toast.makeText(getApplicationContext(), "名称不能为空", Toast.LENGTH_SHORT).show();                } else {                    dialog.dismiss();                }            }        })        .setNegativeButton("取消", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                dialog.dismiss();            }        }).create();try {    Field field = alertDialog.getClass().getDeclaredField("mAlert");    field.setAccessible(true);    //   获得mAlert变量的值    Object obj = field.get(alertDialog);    field = obj.getClass().getDeclaredField("mHandler");    field.setAccessible(true);    //   修改mHandler变量的值,使用新的ButtonHandler    field.set(obj, new ButtonHandler(alertDialog));} catch (Exception e) {}//   显示对话框alertDialog.show();
这样就实现了,要想关闭dialog,必须使用dialog.dismiss()来进行关闭。就变为可控制的啦。


1 0