Android中PopupWindow中如何弹出时让背景变暗

文章目录


一、popupWindow使用

kotlin 复制代码
  val view =
            LayoutInflater.from(this@AudioPlayerActivity).inflate(R.layout.popup_play_list, null)
        //设置pop相关设置
        val height = ScreenSizeUtil.getScreenTotalHeight(this@AudioPlayerActivity) / 5 * 3 //高度占屏幕的3/5
        popupWindow = PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, height, true)
        popupWindow?.setBackgroundDrawable(ColorDrawable()) //随便设置背景防止低版本中出现返回键无法退出的问题
        popupWindow?.showAsDropDown(audioBottom, 0, audioBottom.height) //相对于固定控件的弹出位置,X轴右正左负 Y轴下正上负

二、背景变暗方法

1.工具类

kotlin 复制代码
object BackgroundUtils {


    /**
     *  @describe: 方法1.使用FLAG_DIM_BEHIND给当前界面添加黑色图层,并设置其透明度
     *  @params:
     *  @return:
     */
    fun darkenBackground1(bgcolor: Float, context: Activity) {
        val lp: WindowManager.LayoutParams = context.getWindow().getAttributes()
        lp.alpha = bgcolor // 0.0f完全透明,1.0f完全不透明
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) //添加黑色图层
        context.getWindow().setAttributes(lp) //设置该图层透明度
    }


    /**
     *  @describe:方法2.给RootView添加黑色半透明遮罩层
     *  @params:
     *  @return:
     */
    fun darkenBackground2(bgcolor: Float, context: Activity) {
        //获取根节点作为添加遮罩的容器
        val rootView = context.window.decorView.rootView
        //创建黑色的可绘制对象
        val dra = ColorDrawable(Color.BLACK)
        //设置绘制边界
        dra.setBounds(0,0,rootView.width,rootView.height)
        //根据比例设置透明度
        dra.alpha = (255 * bgcolor).toInt()
        //将drawable添加到视图之上的覆盖层
        rootView.overlay.add(dra)

    }

    fun darkenBackground2Clear(context: Activity) {
        val rootView = context.window.decorView.rootView
        rootView.overlay.clear() //移除掉覆盖层
    }
}

2.使用

kotlin 复制代码
方法1:
//设置弹出时背景变暗
        BackgroundUtils.darkenBackground1(0.5f,this@AudioPlayerActivity)
        popupWindow?.setOnDismissListener { //取消时恢复背景色
            BackgroundUtils.darkenBackground1(1.0f,this@AudioPlayerActivity)
        }

方法2:
//设置弹出时背景变暗
        BackgroundUtils.darkenBackground2(0.5f,this@AudioPlayerActivity)
        popupWindow?.setOnDismissListener { //取消时恢复背景色
            BackgroundUtils.darkenBackground2Clear(this@AudioPlayerActivity)
        }
相关推荐
lizhenjun1142 小时前
android修改线程名字长度
android
用户69371750013846 小时前
Google 正在“收紧侧加载”:陌生 APK 安装或需等待 24 小时
android·前端
用户69371750013846 小时前
Room 3.0:这次不是升级,是重来
android·前端·google
alexhilton9 小时前
Compose中的ContentScale:终极可视化指南
android·kotlin·android jetpack
Digitally12 小时前
2026 年 8 款安卓数据擦除软件和应用对比
android
杨忆12 小时前
android 11以上 截图工具类
android
粤M温同学12 小时前
Android Studio 中安装 CodeBuddy AI助手
android·ide·android studio
阿拉斯攀登13 小时前
【RK3576 安卓 JNI/NDK 系列 08】RK3576 实战(二):JNI 调用 I2C 驱动读取传感器数据
android·安卓ndk入门·jni方法签名·java调用c++·rk3576底层开发·rk3576 i2c开发
赶路人儿14 小时前
常见的mcp配置
android·adb
符哥200814 小时前
充电桩 WiFi 局域网配网(Android/Kotlin)流程、指令及实例说明文档
android·开发语言·kotlin