Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android PopupWindow 失去焦點或點擊空白處自動消失的解法

編輯:關於 Android 程式設計

先來看 Android API 的這個方法:

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.

也就是說,基本上透過這個屬性加上 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 這裡自己也犯了同樣的錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved