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)
        }
相关推荐
不爱说话郭德纲9 小时前
告别漫长的HbuilderX云打包排队!uni-app x 安卓本地打包保姆级教程(附白屏、包体积过大排坑指南)
android·前端·uni-app
Sinclair14 小时前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
雮尘17 小时前
手把手带你玩转Android gRPC:一篇搞定原理、配置与客户端开发
android·前端·grpc
ktl18 小时前
Android 编译加速/优化 80%:一个文件搞定,零侵入零配置
android
alexhilton1 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
冬奇Lab1 天前
InputManagerService:输入事件分发与ANR机制
android·源码阅读
张小潇1 天前
AOSP15 Input专题InputManager源码分析
android·操作系统
RdoZam2 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
奥陌陌2 天前
android 打印函数调用堆栈
android
用户985120035832 天前
Compose Navigation 3 深度解析(二):基础用法
android·android jetpack