效果图

运行效果图

代码如下
import { curves } from '@kit.ArkUI'
@Entry
@Component
struct ScrollExample {
scroller: Scroller = new Scroller()
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
build() {
Stack({ alignContent: Alignment.TopStart }) {
Column(){
Scroll(this.scroller) {
Row() {
ForEach(this.arr, (item: number) => {
Text(item.toString())
.fontColor(Color.Orange)
.width(150)
.height('90%')
.backgroundColor(0xFFFFFF)
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
.margin({ left: 10 })
}, (item: string) => item)
}
.height('50%')
}
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.On)
.scrollBarColor(Color.Gray)
.scrollBarWidth(10)
.friction(0.6)
.edgeEffect(EdgeEffect.None)
.onWillScroll((xOffset: number, yOffset: number, scrollState: ScrollState) => {
console.info(xOffset + ' ' + yOffset)
})
.onScrollEdge((side: Edge) => {
console.info('To the edge')
})
.onScrollStop(() => {
console.info('Scroll Stop')
})
Column({ space: 15 }) {
Button('scroll 150 右滑指定距离150vp')
.onClick(() => {
this.scroller.scrollBy(150, 0)
})
Button('scroll 100')
.onClick(() => {
const xOffset: number = this.scroller.currentOffset().xOffset;
this.scroller.scrollTo({ xOffset: xOffset + 100, yOffset: 0 })
})
Button('scroll 100 with animation')
.onClick(() => {
let curve = curves.interpolatingSpring(10, 1, 228, 30)
const xOffset: number = this.scroller.currentOffset().xOffset;
this.scroller.scrollTo({
xOffset: xOffset + 100,
yOffset: 0,
animation: { duration: 1000, curve: curve }
})
})
Button('back to start')
.onClick(() => {
this.scroller.scrollEdge(Edge.Start)
})
Button('next page')
.onClick(() => {
this.scroller.scrollPage({ next: true, animation: true })
})
Button('fling -3000')
.onClick(() => {
this.scroller.fling(-3000)
})
Button('scroll to end')
.onClick(() => {
this.scroller.scrollEdge(Edge.End, { velocity: 700 })
})
}
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
}
}