前言
程序需要在首页添加一个子功能的入口,这里采用的是在页面上添加一个悬浮球,点击悬浮球即可直接进入功能页面。
话不多说,直接开整...
思路
开发工具:DevEco Studio NEXT Developer Preview2
SdkV:4.1.0(11)
使用给一个视图添加onTouch事件,监听到触摸坐标进行记录,移动坐标时改变视图位置,在松手是判断当前视图是否超出了限制范围,如果超出了自动吸边
效果
开始
这里采用Image做为视图,对它的onTouch事件做对应的处理
build() {
Column() {
Image($r("app.media.moments_float_icon"))
.size({ width: this.viewW, height: this.viewW })
.onTouch((event: TouchEvent) => {
switch (event.type) {
// 按下是记录当前位置坐标
case TouchType.Down: {
this.px = event.touches[0].x
this.py = event.touches[0].y
break
}
// 移动时改变position
case TouchType.Move: {
this.gx = event.touches[0].windowX - this.px
this.gy = event.touches[0].windowY - this.py
break
}
// 松手时如果超出了屏幕,调整为吸附边框
case TouchType.Up: {
if (this.gx > this.screenW / 2) {
this.gx = this.screenW - this.viewW
} else {
this.gx = 0
}
if (this.gy > this.screenH - this.viewW - 50) {
this.gy = this.screenH - this.viewW - 50
} else if (this.gy < 20) {
this.gy = 20
}
break
}
}
})
.onClick(() => {
this.floatOnClick ? this.floatOnClick() : null
})
}
.position({ x: this.gx, y: this.gy })
.borderRadius(this.viewW / 2)
}
调用
最后是调用关键在于position和zIndex
position:因为呈现悬浮态,所以要设置初始绝对坐标需要设置该视图的坐标
zIndex :将悬浮视图置于最上层
XPFloatView({
gx: "85%", gy: "90%", // 起始坐标位置
floatOnClick: () => {
ToastUtils.show("点击了按钮")
}
})
.position({ x: 0, y: 0 })// 这里要设置初始坐标,才能最好的保证呈现悬浮状态
.zIndex(1) // 置于窗口最上层