设置popWindow背景变暗

1.//popWindow命名为window。

//首先给window设置一个背景颜色

  ColorDrawable cd = new ColorDrawable(0x000000);
  window.setBackgroundDrawable(cd);
  // 产生背景变暗效果,设置透明度
  WindowManager.LayoutParams lp = getWindow().getAttributes();
  lp.alpha = 0.4f;

//之前不写这一句也是可以实现的,这次突然没效果了。网搜之后加上了这一句就好了。据说是因为popUpWindow没有getWindow()方法。
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
  getWindow().setAttributes(lp);

//这样就设置好了变暗的效果

2.//然后再设置退出popupwindow时取消暗背景

window.setOnDismissListener(new OnDismissListener() {
   
   @Override
   public void onDismiss() {
    //在dismiss中恢复透明度
    WindowManager.LayoutParams lp=getWindow().getAttributes();
    lp.alpha=1f;

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    getWindow().setAttributes(lp);
   }
  });

//这样写效率不高,代码重复。优化之后:

private void darkenBackgroud(Float bgcolor) {
  WindowManager.LayoutParams lp = getWindow().getAttributes();
  lp.alpha = bgcolor;
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
  getWindow().setAttributes(lp);
 }

调用时:

1.使变暗:darkenBackgroud(0.4f);

2.使恢复:darkenBackgroud(1f);

原文地址:https://www.cnblogs.com/fanerblog/p/4856384.html