网站首页 > 知识剖析 正文
前言
为了增加应用程序功能的丰富性和便利性,很多应用都会提供一个悬浮窗口实现多页面显示。特别是一些性能检测工具,比如 dokit 。在鸿蒙上怎么实现类似的全局悬浮窗口呢?阅读完本篇文章你将学会在鸿蒙上如何实现这一功能。
实现效果
需求分析
要想实现全局悬浮窗口,必须满足以下几个要求:
- 窗口可以悬浮在任意页面。
- 窗口可以跟随手势拖动。
- 边界处理。
技术实现
在 ArkUI 中,页面只有 Window 和 View 两种组成。View 通常都是显示在 Window 中,如果要想实现一个可以在任意页面都能停留显示的悬浮窗,只能通过 window 来实现。
- 通过 windowState 调用 createSubWIndow 来创建一个子 Window。
this.windowState.createSubWindow("subWindow", (err: BusinessError, window) => {
})
- 对于 windowState 的获取,一般都在 EntryAbility 中的 onWindowStateCreate 中提供,如果不想通过传递参数的方式获取 windowStage,系统也提供了工具类可以在任意地方获取。
//存储windowStage
WindowManager.setWindowStage(windowStage);
//获取windowstage
this.windowState = WindowManager.getWindowStage()
- 初始化 Window。url 为 window 页面的路径。
window.setWindowLayoutFullScreen(false) //设置window是否全屏显示
window.setUIContent(url, (error) => {
window.showWindow((error) => {
window.setWindowBackgroundColor("#00000000") //设置window背景色
})
})
window.resize(this.size, this.size)//设置window大小
window.moveWindowTo(this.locationX, this.locationY) //设置window的初始位置
- 手势移动,通过调研 PanGesture()的 onActionUpdate 方法不断更新 window 的位置。
.gesture(GestureGroup(
GestureMode.Exclusive,
PanGesture().onActionUpdate((event)=>{
this.currentWindow?.moveWindowTo(event.offsetX,event.offsetY)
})
))
- 边界处理,计算最小移动范围和最大移动范围。确保 window 不会移出当前页面。
this.locationX = Math.min(Math.max(this.locationX + x, this.minX), this.maxX)
this.locationY = Math.min(Math.max(this.locationY + y, this.minY), this.maxY)
- window 销毁。当退出应用时,需要将 window 关闭,调用 window 的 destroyWindow 方法销毁 window。
this.contentWindow.destroyWindow(() => {
this.contentWindow = undefined
})
总结
通过 window 不仅能实现全局悬浮窗,还可以实现自定义弹窗,Poupwindow,toast 等一系列弹窗。使用 window 的好处在于可以彻底和当前页面分离,不依赖页面存在。可以实现在任意地方弹窗。快动手试试吧!
猜你喜欢
- 2025-06-10 LeetCode 力扣官方题解 | 521. 最长特殊序列Ⅰ
- 2025-06-10 进一步理解函数(进一步理解函数的方法)
- 2025-06-10 二维码能跑游戏?开发者 3KB 复刻 DOOM 崩溃,ChatGPT 救场
- 2025-06-10 数据结构:布隆过滤器(Bloom Filter)
- 2025-06-10 数据质量动态探查及相关前端实现(数据质量检查方法)
- 2025-06-10 一文搞懂堆外内存(模拟内存泄漏)(堆内存 堆外内存)
- 2025-06-10 JavaScript中计算数组中的最大值/最小值
- 2025-06-10 JavaScript展开运算符与剩余参数,灵活操作数组与对象的终极利器
- 2025-06-10 为什么 MapReduce 再次流行起来了?
- 2025-06-10 java Math类和Random类的用法(java中的random怎么用)
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)