大家想必對PopupWindow不會很陌生吧澳眷,我們在開發(fā)中經(jīng)常會遇到要求使其背景半透明的需求,但網(wǎng)上的很多解決方案只能是在大部分機型上滿足要求甫题,像華為這樣的機型就會發(fā)現(xiàn)我們原來設置的背景變暗效果的代碼并沒有起效果派敷。
這里我貼出最終的兼容方案:
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);
// 產(chǎn)生背景變暗效果
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);
注:特別是下面幾行代碼
// 產(chǎn)生背景變暗效果
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);
}
});
網(wǎng)上很多方案都要求加下面這兩行代碼,但其實加上反而會影響華為這種機型的顯示效果
ColorDrawable dw = new ColorDrawable(-00000);
popupWindow.setBackgroundDrawable(dw);