
回复
为了增加应用程序功能的丰富性和便利性,很多应用都会提供一个悬浮窗口实现多页面显示。特别是一些性能检测工具,比如 dokit 。在鸿蒙上怎么实现类似的全局悬浮窗口呢?阅读完本篇文章你将学会在鸿蒙上如何实现这一功能。
要想实现全局悬浮窗口,必须满足以下几个要求:
在 ArkUI 中,页面只有 Window 和 View 两种组成。View 通常都是显示在 Window 中,如果要想实现一个可以在任意页面都能停留显示的悬浮窗,只能通过 window 来实现。
this.windowState.createSubWindow("subWindow", (err: BusinessError, window) => {
})
//存储windowStage
WindowManager.setWindowStage(windowStage);
//获取windowstage
this.windowState = WindowManager.getWindowStage()
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的初始位置
.gesture(GestureGroup(
GestureMode.Exclusive,
PanGesture().onActionUpdate((event)=>{
this.currentWindow?.moveWindowTo(event.offsetX,event.offsetY)
})
))
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)
this.contentWindow.destroyWindow(() => {
this.contentWindow = undefined
})
通过 window 不仅能实现全局悬浮窗,还可以实现自定义弹窗,Poupwindow,toast 等一系列弹窗。使用 window 的好处在于可以彻底和当前页面分离,不依赖页面存在。可以实现在任意地方弹窗。快动手试试吧!