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)
        }
相关推荐
darkb1rd1 天前
五、PHP类型转换与类型安全
android·安全·php
gjxDaniel1 天前
Kotlin编程语言入门与常见问题
android·开发语言·kotlin
csj501 天前
安卓基础之《(22)—高级控件(4)碎片Fragment》
android
峥嵘life1 天前
Android16 【CTS】CtsMediaCodecTestCases等一些列Media测试存在Failed项
android·linux·学习
stevenzqzq1 天前
Compose 中的状态可变性体系
android·compose
似霰1 天前
Linux timerfd 的基本使用
android·linux·c++
darling3311 天前
mysql 自动备份以及远程传输脚本,异地备份
android·数据库·mysql·adb
你刷碗1 天前
基于S32K144 CESc生成随机数
android·java·数据库
TheNextByte11 天前
Android上的蓝牙文件传输:跨设备无缝共享
android
言之。1 天前
Kotlin快速入门
android·开发语言·kotlin