鸿蒙自定义进度条(滑动条)替换HarmonyOS-slider
·
因为鸿蒙进度条使用时无法获取到点击的位置所以有些打点业务无法完成便新增自定义进度条
点击事件处理进度条跳转位置
滑动事件处理进度条滑动后位置
import { componentUtils } from '@kit.ArkUI'
@Entry
@Component
export struct SliderGXYLXY {
@Prop total: number = 0
@Prop @Watch('valueChangeAction') value: number = 0
@State private progressWidth: number = 200
@State private positionX: number = 0
@State private offsetX: number = 0;
@State private paning: boolean = false;
valueChange: (value: number) => void = () => {
}
valueChangeAction() {
this.positionX = this.progressWidth * this.value / this.total
if (this.positionX >= this.progressWidth) {
this.positionX = this.progressWidth
}
if (this.positionX <= 0) {
this.positionX = 0
}
}
aboutToAppear(): void {
setTimeout(() => {
this.progressWidth = px2vp(componentUtils.getRectangleById('gxy_progress').size.width)
this.positionX = this.progressWidth * this.value / this.total
}, 20)
}
build() {
Stack({ alignContent: Alignment.Start }) {
Row() {
}
.width('100%')
.height(10)
.borderRadius(2)
.backgroundColor(Color.Black)
.opacity(0.5)
.onClick((event: ClickEvent) => {
if (event) {
this.offsetX = event.x;
if (this.offsetX >= this.progressWidth) {
this.offsetX = this.progressWidth
}
if (this.offsetX <= 0) {
this.offsetX = 0
}
this.positionX = this.offsetX;
this.value = Math.round(this.total * this.positionX / this.progressWidth)
this.valueChange(this.value)
}
})
Row() {
Row()
.width(this.paning ? this.offsetX : this.positionX)
.height(10)
.borderRadius(2)
.backgroundColor(Color.Black)
.hitTestBehavior(HitTestMode.None)
Row() {
}
.width(15)
.height(15)
.borderRadius(7.5)
.backgroundColor(Color.White)
.margin({ left: -7 })
.gesture(
// 绑定拖动手势
PanGesture()
.onActionStart((event: GestureEvent | undefined) => {
console.info('Pan start');
this.paning = true
})// 当触发拖动手势时,根据回调函数修改组件的布局位置信息
.onActionUpdate((event: GestureEvent | undefined) => {
if (event) {
this.offsetX = this.positionX + event.offsetX;
if (this.offsetX >= this.progressWidth) {
this.offsetX = this.progressWidth
}
if (this.offsetX <= 0) {
this.offsetX = 0
}
let rate = this.offsetX / this.progressWidth
let currentValue = Math.round(this.total * rate)
this.valueChange(currentValue)
}
})
.onActionEnd(() => {
this.paning = false
this.positionX = this.offsetX;
if (this.positionX >= this.progressWidth) {
this.positionX = this.progressWidth
}
if (this.positionX <= 0) {
this.positionX = 0
}
this.value = Math.round(this.total * this.positionX / this.progressWidth)
this.valueChange(this.value)
})
)
}.hitTestBehavior(HitTestMode.None)
}
.id('gxy_progress')
.height(15)
.width(this.progressWidth)
}
}
更多推荐


所有评论(0)