1. 程式人生 > >Android popupwindow 失去焦點或者點擊空白區域時消失的解決方法

Android popupwindow 失去焦點或者點擊空白區域時消失的解決方法

override -m its 順序 his false 讓其 rop make

先來看下Android API 的這個Methods:

public void setOutsideTouchable (boolean touchable)

Controls whether the pop-up will be informed of touch events outside of its window. This only makes sense for pop-ups that are touchable but not focusable, which means touches outside of the window will be delivered to the window behind. The default is false.

If the popup is showing, calling this method will take effect only the next time the popup is shown or through a manual call to one of the update()

methods.

Parameters

touchable true if the popup should receive outside touch events, false otherwise
See Also
  • isOutsideTouchable()
  • isShowing()
  • update()


就是說,基本通過這個屬性和setFocusable(true);就能實現點擊別的區域讓popup消失,

也能夠這樣做,設置點擊popup窗口自身,讓其消失,通過下邊的方法即root重寫onTouch方法:

 //點擊窗口,PopupWindow消失           
                root.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        popup.dismiss();
                        return true;
                    }
                });

相同, 能夠不用重寫root的onTouch方法,而該重寫 Activity的onTouchEvent()方法,正常情況下也能實現popup消失.


  @Override
    public boolean onTouchEvent(MotionEvent event) {  
        if (popup != null && popup.isShowing()) { 
            popup.dismiss(); 
            popup= null; 
        } 
        return super.onTouchEvent(event);
    }

可是, 我遇到一個問題,就是上述的方法都解決不了, 是什麽原因?

事實上,罪魁禍首就是, popup的代碼順序, 手賤先調用了 showAsDropDown()方法,在設置其它屬性,導致了這樣的情況.

showAsDropDown這種方法相當於 Dialog.show()方法, 假設是先show了, 然後其它屬性即使是設置了,也起不到應有的作用.

這一點,常常提醒別人,沒想到到popup這裏我犯了相同的錯誤.


Android popupwindow 失去焦點或者點擊空白區域時消失的解決方法