mDg = new Dialog(getActivity());
mDg.setOnKeyListener(mVolPancelListener);
Window win = mDg.getWindow();
WindowManager.LayoutParams lp = win.getAttributes();
win.setBackgroundDrawableResource(R.drawable.none);
lp.x = 206;
lp.y = -165;
win.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mDg.setCanceledOnTouchOutside(true);
mDg.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDg.setContentView(mVolumeView);
说下Dialog的衍生AlertDialog,这个有个很讨厌的是点击相应钮,dialog就会消失,google了下解决办法,1,自绘view,然后放到dialog中,2,使用反射的方法,给alertdialog重置一个handler,代码如下
/* * define our own button handler, do not deal with dismiss message. */ class ButtonHandler extends Handler { private WeakReference<DialogInterface> mDialog; //弱引用 public ButtonHandler(DialogInterface dialog) { mDialog = new WeakReference<DialogInterface>(dialog); } 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,其中参数dialog应该是new AlertDialog.Builder(mContext).create(),并且已经定义了view和响应事件的。
private void popUpDialog(AlertDialog dialog) { /* * alert dialog's default handler will always close dialog whenever user * clicks on which button. we have to replace default handler with our * own handler for blocking close action. * Reflection helps a lot. */ try { Field field = dialog.getClass().getDeclaredField("mAlert"); field.setAccessible(true); //retrieve mAlert value Object obj = field.get(dialog); field = obj.getClass().getDeclaredField("mHandler"); field.setAccessible(true); //replace mHandler with our own handler field.set(obj, bHandler); } catch (SecurityException e) { } catch (NoSuchFieldException e) { } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } //we can show this dialog now. dialog.show(); }
在dialog的dismiss的时候,如果它所在的context,比如说activity已经被finish了,会有java.lang.illegalargumentexception: view not attached to window manager异常。
在A中启动B,B中有线程操作,结束时涉及到对话框的dismiss。如果在操作尚未结束时,按下HOME键,线程后台操作。此时重新进去A,等到线程操作完成就会出现这个异常。此时应该做一个判断,如下:
// Dismiss the Dialog only when the parent Activity is still alive.