Android 基于 PopupWindow 实现右下角的悬浮额外指标数值

文章目录

    PopupWindow 介绍

    This class represents a popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.

    PopupWindow 会浮动在当前 Activity/Fragment 之上。

    相对于 AlertDialog,PopupWindow 的实现更灵活。

    • 可以自定义位置。例如显示在指定按钮的下方,上方等位置。
    • 展现形式更自由。不需要像 AlertDialog 显示在屏幕中央,也没有遮罩层。实现作为一个悬浮菜单。

    布局代码

    放在一个独立的 layout.xml 文件中,例如

    popup_metrics.xml

    然后关联到 PopupWindow 上。

    示例代码

    // 创建 PopupWindow 的内容视图
    val contentView = layoutInflater.inflate(R.layout.popup_metrics, null)
    
    // 创建 PopupWindow 对象
    popupWindow = PopupWindow(
        contentView,
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT,
        true
    )
    

    宽高问题

    如果想实现 PopupWindow 的宽高等同于 Layout 文件中设置的宽高。

    就需要在初始化 PopupWindow 时,设置为 WRAP_CONTENT。

    同时,Layout XML 中,最外层设置为 wrap_content, 然后内嵌一个指定 dp 宽高的容器。

    数据监听

    例如,通过监听 ViewModel 中的 LiveData 来更新 PopupWindow 中的数据:

    val item = contentView.findViewById<TextView>(R.id.item)
    viewModel.someValue.observe(
        viewLifecycleOwner, Observer {
            val value = it.toUShort().toString()
            it?.let {
                item.text = someValue
            }
        }
    )
    

    参考

    • https://www.codingninjas.com/studio/library/popup-window-in-android
    • https://blog.csdn.net/qq_20451879/article/details/72320325

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式