Android PopupWindow实现遮罩层效果

作者:袖梨 2022-06-25

此篇博客实现的功能是:点击界面中的图片,跳出一个PopupWindow,PopupWindow中含有相应的文字和图标,并且在显示PopupWindow的时候,背景为半透明。

看图描述:点击加号,跳出PopupWindow,其中包含三个图片,点击叉号PopupWindow消失;当PopupWindow显示的时候,背景为半透明

显示PopupWindow的代码

private void showPopupWindow() {
  View view = (LinearLayout) getLayoutInflater().inflate(R.layout.popup_window_layout, null);
  ImageView ivP = (ImageView) view.findViewById(R.id.ivP);
  ImageView ivX = (ImageView) view.findViewById(R.id.ivX);
  ImageView ivClose = (ImageView) view.findViewById(R.id.ivClose);
  LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT);
  ivP.setLayoutParams(params);
  ivX.setLayoutParams(params);
  ivClose.setLayoutParams(params);
  ivClose.setOnClickListener(this);
  popupWindow = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
  popupWindow.setContentView(view);
  popupWindow.setFocusable(true);
  popupWindow.setTouchable(true);
  popupWindow.setOutsideTouchable(false);
  popupWindow.showAsDropDown(ivAdd, 0, 0);
  backgroundAlpha(0.4f);
 }
private void backgroundAlpha(float f) {
  WindowManager.LayoutParams lp =getWindow().getAttributes(); 
  lp.alpha = f; 
  getWindow().setAttributes(lp);
 }

backgroundAlpha()方法用于设置PopupWindow显示后的背景半透明,参数 f 的范围是0.0~1.0,数值越大透明度越高。

源码下载

相关文章

精彩推荐