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)
        }
相关推荐
TheNextByte12 小时前
iPhone 与Android :有什么区别?
android·cocoa·iphone
_李小白2 小时前
【Android 美颜相机】第二十一天:GPUImageChromaKeyBlendFilter (颜色加深混合滤镜)
android·数码相机
yantaohk3 小时前
【2025亲测】中兴B860AV3.2M完美刷机包ATV版本安卓9-解决1G运存BUG,开ADB已ROOT
android·嵌入式硬件·adb·云计算
乐观勇敢坚强的老彭4 小时前
c++信奥寒假营集训01
android·java·c++
kdniao14 小时前
PHP 页面中如何实现根据快递单号查询物流轨迹?对接快递鸟在途监控 API 实操
android·开发语言·php
言之。4 小时前
MacBook M3 Pro:React Native 安卓开发
android·react native·react.js
感觉不怎么会5 小时前
Android 13 - 对讲app后台休眠后无法录音
android·linux
Minilinux20185 小时前
Android系列之 屏幕触控机制(一)
android·屏幕触控·andorid touch·viewroot
冰语竹6 小时前
Android学习-随笔(安装后设置路径)
android·学习