下面这段PopupWindow弹出时背景变暗效果的代码在网上随处可见:
private void setBackgroundAlpha(float bgAlpha){
WindowManager.LayoutParams layoutParams = MainActivity.this.getWindow().getAttributes();
layoutParams.alpha = bgAlpha; //0.0-1.0
MainActivity.this.getWindow().setAttributes(layoutParams);
}
我之前也是用这段代码实现这个效果,真机调试并没有什么问题。后来产品发布后有用户反馈背景透明,字体显示不清,陆续又出现几例这种情况,都是华为的手机。在网搜索了好久,都没找到解决办法,今天终于解决了。很简单,只要多加一句代码就行,如下:
- private void setBackgroundAlpha(float bgAlpha){
- WindowManager.LayoutParams layoutParams = MainActivity.this.getWindow().getAttributes();
- layoutParams.alpha = bgAlpha; //0.0-1.0
- MainActivity.this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//多加这一句,问题就解决了!这句的官方文档解释是:让窗口背景后面的任何东西变暗
- MainActivity.this.getWindow().setAttributes(layoutParams);
- }