Android popupwindow和dialog監聽返回鍵


使用情況: 
在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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM