2013-03-22 59 views
4

我在試着測試PopupWindow類。我創建這個方法來顯示彈出:PopupWindow TouchInterceptor不能正常工作

public void showPopup(){ 
      LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE); 
      View popupView = layoutInflater.inflate(R.layout.popup, null); 
      final PopupWindow popup = new PopupWindow(popupView, 
         LayoutParams.WRAP_CONTENT, 
         LayoutParams.WRAP_CONTENT); 
      popup.setOutsideTouchable(true); 
      popup.setTouchable(true); 
      popup.setTouchInterceptor(new OnTouchListener() { 
       @Override 
       public boolean onTouch(View v, MotionEvent event) { 
        Log.d("POPUP", event.toString()); 
        if(event.getAction() == MotionEvent.ACTION_OUTSIDE){ 
         popup.dismiss(); 
         return true; 
        } 
        return true; 
       } 
      }); 
      popup.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 200); 
} 

彈出正確顯示,順便似乎觸摸攔截沒有在所有的工作:我沒有得到任何的日誌信息和當然,彈出窗口如果在窗口之外按下,它並不會被解僱。

是否有一些進一步的屬性,我必須在彈出窗口或活動主機中設置?

+0

我有這個相同的問題,讓我記得我是如何修復它。 – a54studio 2013-03-22 12:53:35

回答

5
pw.setBackgroundDrawable (new BitmapDrawable()); 
pw.setFocusable(false); 
pw.setOutsideTouchable(true); 

使用此代碼,希望如果你想要做一些動作,這是有幫助的

+0

嗨,我一直在工作的一段代碼,其中有一個彈出窗口內的列表。所以我希望它是可以聚焦的。如何處理任何外部觸摸事件以解除此彈出窗口。在我的下一個評論,我會貼上我的做法 – 2013-08-21 05:35:53

+0

popupWindow.setTouchInterceptor(新OnTouchListener(){ \t \t \t \t @覆蓋 \t \t \t \t公共布爾onTouch(視圖V,MotionEvent事件){ \t \t \t \t \t popupWindow .dismiss(); \t \t \t \t \t如果(event.getAction()== MotionEvent.ACTION_OUTSIDE){ \t 012 (TAG,「有些事件發生在窗外:行動在外面」); \t \t \t \t \t \t \t \t \t \t \t \t迴歸真實; \t \t \t \t \t} \t \t \t \t \t Log.e(TAG, 「一些事件發生的外窗」); \t \t \t \t \t \t \t \t \t \t返回FALSE; \t \t \t \t} \t \t \t}); – 2013-08-21 05:36:32

+0

你只是刪除你的代碼段,並添加我的上面的代碼,希望它能工作 – Karthi 2013-08-21 07:14:00

2

,當它被點擊窗外,你需要真正的既setFocusable() + setOutsideTouchable(),您可以考慮使用setOnDismissListener。這是方法onDismiss被稱爲,如預期,當對話框對話框被取消:

PopupWindow mPopupWindow = new PopupWindow(mRootView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT); 
    mPopupWindow.setBackgroundDrawable(new ColorDrawable(android.R.color.transparent)); 
    mPopupWindow.setFocusable(true); 
    mPopupWindow.setOutsideTouchable(true); 
    mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { 
     @Override 
     public void onDismiss() { 
     // some action .... 
     } 
    }); 
+0

我試着用你的解決方案它效果很好。然而,一旦這個函數執行,如果我點擊任何按鈕應用程序崩潰,說明錯誤'java.lang.IllegalStateException:指定的孩子已經有一個父。你必須首先調用孩子父母的removeView()。「試圖找出解決辦法,但沒有達到。有什麼建議嗎? – Sabarish 2015-12-04 17:12:07

+0

當您嘗試多次將視圖添加到視圖層次結構時,會發生這種情況。你應該尋找'addView()'或'getLayoutInflater()。inflate(R.layout.xyz,parentView,true)''。 – skywall 2015-12-05 22:22:08