最近有個項目,用到了popupwindow,還是在一個activity中用到了多個popupwindow,這就是涉及到popupwindow間的切換了。但每次彈出popupwindow後,想通過點擊外部控件進行進行popupwindow間的切換,會發現點擊外部控件的時候,只響應了隱藏當前popupwindow的事件,外部控件的點擊事件並沒有執行,需再次點擊外部控件,才彈出popupwindow,這主要是焦點導致的,因爲彈框焦點默認設置的是true,所以點擊其他按鈕,不會觸發其他按鈕對應的事件,因爲焦點不在那個按鈕上。所以只要設置成false就好了。
代碼如下: 注意要在顯示前加上popupWindow.setFocusable(false);設置不獲取焦點
PopupWindow popupWindow = new PopupWindow(popupWindow_view, 200,LayoutParams.MATCH_PARENT, true);
popupWindow.setWidth(500);
popupWindow.setFocusable(false); // 設置PopupWindow不獲得焦點
int[] location = new int[2];
// 這裏是位置顯示方式,在屏幕的左側
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY,location[0] + view.getWidth(), location[1]);
// 添加監聽
View popupWindow_view.setFocusableInTouchMode(true);
popupWindow.setOutsideTouchable(true);
// // 點擊其他地方消失
popupWindow_view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
popupWindow = null;
}
return false;
}
});
這樣,在點擊外部控件時,會先關閉當前popupwindow再執行外部控件的點擊事件,其實就是一個獲取焦點的問題,並不像網上說的那麼麻煩。