Android PopupWindow背景半透明兼容方案
大家想必對PopupWindow不會很陌生吧,我們在開發中經常會遇到要求使其背景半透明的需求,但網上的很多解決方案只能是在大部分機型上滿足要求,像華為這樣的機型就會發現我們原來設置的背景變暗效果的代碼并沒有起效果。
這里我貼出最終的兼容方案:
View contentView;
LayoutInflater mLayoutInflater = LayoutInflater.from(activity);
contentView = mLayoutInflater.inflate(R.layout.layout_popupwindow,
null);
pop = new PopupWindow(contentView,
ViewGroup.LayoutParams.MATCH_PARENT, (int) context.getResources().getDimension(R.dimen.y568));
TextView tvTitle = (TextView) contentView.findViewById(R.id.text);
tvTitle.setText(strTitle);
ListView listView = (ListView) contentView.findViewById(R.id.list);
// 產生背景變暗效果
WindowManager.LayoutParams lp = activity.getWindow()
.getAttributes();
lp.alpha = 0.4f;
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
activity.getWindow().setAttributes(lp);
pop.setTouchable(true);
pop.setFocusable(true);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setOutsideTouchable(true);
pop.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
pop.update();
pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
// 在dismiss中恢復透明度
public void onDismiss() {
WindowManager.LayoutParams lp = activity.getWindow()
.getAttributes();
lp.alpha = 1f;
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
activity.getWindow().setAttributes(lp);
}
});
listView.setOnItemClickListener(onItemClickListener);
listView.setAdapter(adapter);
注:特別是下面幾行代碼
// 產生背景變暗效果
WindowManager.LayoutParams lp = activity.getWindow()
.getAttributes();
lp.alpha = 0.4f;
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
activity.getWindow().setAttributes(lp);
pop.setTouchable(true);
pop.setFocusable(true);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setOutsideTouchable(true);
pop.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
pop.update();
pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
// 在dismiss中恢復透明度
public void onDismiss() {
WindowManager.LayoutParams lp = activity.getWindow()
.getAttributes();
lp.alpha = 1f;
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
activity.getWindow().setAttributes(lp);
}
});
網上很多方案都要求加下面這兩行代碼,但其實加上反而會影響華為這種機型的顯示效果
ColorDrawable dw = new ColorDrawable(-00000);
popupWindow.setBackgroundDrawable(dw);
來自:http://www.androidchina.net/5674.html
本文由用戶 MarKwan 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!