popupwindow和dialog监听返回键

来源:互联网 发布:淘宝优站9.9 编辑:程序博客网 时间:2024/06/05 15:39

使用情况:
在activity中,出现了popupwindow和dialog,这个时候,如果点击返回键,它们消失了,但是一些操作还在继续。如:1、进行耗时操作,出现dialog提醒用户等待,这时,按下返回键,dialog消失,但是,耗时操作还在继续。这是因为,dialog拦截了返回键,消费了它,让自己消失,但是其他进程还在继续。2、一个activity(A),start了新activity(B),B要展示一个popupwindow,这时,按下返回键,popupwindow消失了,但是B还在。我要的效果是:按下返回键,popupwindow消失,B做finish
代码讲解:
1、popupwindow
需要导包

import android.view.View.OnKeyListener;
View popupWindowView = LayoutInflater.from(context).inflate(R.layout.select_layout, null);        popupWindow = new PopupWindow(popupWindowView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);        popupWindow.setAnimationStyle(R.style.SelectAnimationShow);        // 菜单背景色        ColorDrawable dw = new ColorDrawable(0x00ffffff);        popupWindow.setBackgroundDrawable(dw);        popupWindow.showAtLocation(LayoutInflater.from(context).inflate(R.layout.select_activity_layout, null),                Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);        popupWindow.setFocusable(true);        popupWindowView.setFocusable(true);        popupWindowView.setFocusableInTouchMode(true);        popupWindowView.setOnKeyListener(new OnKeyListener() {            @Override            public boolean onKey(View v, int keyCode, KeyEvent event) {                //do something...                return true;            }        });

**注:**PopupWindow的构造函数,一定,一定要用上面写的那种,其他的,没效果或者出错。原因不清楚。
这样写了以后,出现popupwindow时,点击返回键,popupwindow消失,activity-B也会走到onDestroy()这个生命周期


2、dialog

DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener(){        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {            if (keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0)            {                //do something...                return false;            }            else            {                return true;            }        }    } ;

最后

mWaitingDialog.setOnKeyListener(keylistener);
0 2
原创粉丝点击