2015年12月24日 星期四

Android 實戰記錄 (18) - PopupWindow 點擊以外消取問題,Back鍵問題

遇到某些手機,點擊以外範圍無效的狀況,
及Back鍵要如何也有取消的功能

花了不少時間找,應該以下這個連結能夠解決問題
http://blog.csdn.net/woshicaixianfeng/article/details/7075066

及量測 measure 時,會有平版發生Exception

只好把我改過的PopupWindow改成如下

LayoutInflater layoutInflater =(LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup_setting, null);
popupWindow = new PopupWindow(popupView,ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
RelativeLayout lay_popwin = (RelativeLayout) popupView.findViewById(R.id.lay_popwin);
lay_popwin.setOnKeyListener(new View.OnKeyListener() {
   public boolean onKey(View v, int keyCode, KeyEvent event) {
      if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK)
         popupWindow.dismiss();
      return false;
   }
});

int xOffset = 0;
try {
   popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
   xOffset = -(popupView.getMeasuredWidth() - popupView.getWidth());
}catch (Exception ex) {
   DisplayMetrics displayMetrics = new DisplayMetrics();
   this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
   //平版measure出錯,直接處理xOffset   //依比例調整xOffset   int dp = 150;//popupWindow 為 150 dp   xOffset = -(int)(dp*displayMetrics.scaledDensity);
   ex.printStackTrace();
}

//解決點外無法取消Popup Window問題popupWindow.setBackgroundDrawable(new BitmapDrawable());
// 使其聚集popupWindow.setFocusable(true);
// 设置允许在外点击消失popupWindow.setOutsideTouchable(true);
//刷新状态(必须刷新否则无效)popupWindow.update();
popupWindow.showAsDropDown(btn_setting, xOffset + 70, -10);


沒有留言:

張貼留言