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)
        }
相关推荐
SharpCJ8 小时前
Android 开发者为什么必须掌握 AI 能力?端侧视角下的技术变革
android·ai·aigc
_李小白9 小时前
【OSG学习笔记】Day 38: TextureVisitor(纹理访问器)
android·笔记·学习
JJay.9 小时前
Kotlin 高阶函数学习指南
android·开发语言·kotlin
jinanwuhuaguo9 小时前
截止到4月8日,OpenClaw 2026年4月更新深度解读剖析:从“能力回归”到“信任内建”的范式跃迁
android·开发语言·人工智能·深度学习·kotlin
JJay.10 小时前
Android Kotlin 协程使用指南
android·开发语言·kotlin
BLUcoding11 小时前
Android 布局介绍
android
summerkissyou198711 小时前
android-蓝牙-状态和协议值总结及监听例子
android·蓝牙
徒 花11 小时前
数据库知识复习05
android·数据库
提子拌饭13313 小时前
番茄时间管理:鸿蒙Flutter 实现的高效时间管理工具
android·flutter·华为·架构·开源·harmonyos·鸿蒙
4311媒体网13 小时前
帝国CMS二次开发实战:精准实现“最新资讯”标识与高亮判断
android