在HarmonyOS NEXT开发中动态修改List不让它滑动?手指再下滑一段距离,页面会跟手下滑一段距离,如果再上滑,此时页面+List都会上滑,需要List能动态设置滑动还是不滑动
在HarmonyOS NEXT开发中动态修改List不让它滑动?手指再下滑一段距离,页面会跟手下滑一段距离,如果再上滑,此时页面+List都会上滑,需要List能动态设置滑动还是不滑动
在HarmonyOS NEXT中,可以通过scrollable
属性动态控制List的滚动能力。结合手势判断实现步骤如下:
绑定滚动状态变量
@State isListScrollEnable: boolean = true // 控制List是否可滚动
在List组件中动态控制滚动
List() {
//...列表项
}
.scrollable(this.isListScrollEnable) // 动态绑定滚动状态
方案一:使用Scroll事件监听
Column() {
List() {
//...
}
.onScroll((_, offsetY: number) => { // 监听滚动偏移量
if (offsetY > 5 && !this.isReachTop) {
// 下滑且不在顶部时禁止List滚动
this.isListScrollEnable = false
} else if (offsetY -5) {
// 上滑时恢复滚动
this.isListScrollEnable = true
}
})
}
方案二:使用组合手势判断
Column()
.gesture(
PanGesture()
.onActionUpdate((event: GestureEvent) => {
if (event.offsetY > 10) { // 下滑超过阈值
this.isListScrollEnable = false
} else if (event.offsetY -10) { // 上滑超过阈值
this.isListScrollEnable = true
}
})
)
补充说明:
scrollEdge
判断列表边界状态.friction(0)
关闭滚动惯性示例完整代码片段:
@Entry
@Component
struct SmartListDemo {
@State isScrollEnabled: boolean = true
@State isReachTop: boolean = true
build() {
Column() {
List({ space: 10 }) {
ForEach(this.items, (item) => {
ListItem() {
Text(item).height(100)
}
})
}
.scrollable(this.isScrollEnabled)
.onScroll((_, offsetY) => {
if (offsetY > 5 && !this.isReachTop) {
this.isScrollEnabled = false
} else if (offsetY -5) {
this.isScrollEnabled = true
}
})
.onScrollEdge((edge) => {
this.isReachTop = (edge === Edge.Top)
})
}
.height('100%')
.backgroundColor(Color.White)
}
}
List参考使用enableScrollInteraction方法,参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-refere...