如何知道Scroll组件目前显示到最后一个item的角标(HarmonyOS 鸿蒙Next)
如何知道Scroll组件目前显示到最后一个item的角标(HarmonyOS 鸿蒙Next) 【设备信息】Mate60
【API版本】Api13
【DevEco Studio版本】5.0.7.200
【问题描述】
如何知道Scroll组件,目前显示到的最后一个item的角标?
4 回复
参考以下示例:
import { curves, display, window } from '@kit.ArkUI'
@Entry
@Component
struct ScrollExample {
scroller: Scroller = new Scroller()
private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@State screenHeight: number = 0
@State stateHeight: number = 0
@State itemHeight: Length = 0
@State itemSep: Length = 10
aboutToAppear() {
display.getAllDisplays((err, data) => {
let screenHeight: number = data[0].height
this.screenHeight = px2vp(screenHeight)
})
}
build() {
Stack({ alignContent: Alignment.TopStart }) {
Scroll(this.scroller) {
Column() {
ForEach(this.arr, (item: number) => {
Column(){
Text(item.toString())
.width('90%')
.height(150)
.backgroundColor(0xFFFFFF)
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
}
.margin({ top: this.itemSep })
.onAreaChange((oldValue: Area, newValue: Area) => {
console.info(`Ace: on area change, oldValue is ${newValue.height}`)
let ss = newValue.height
})
}, (item: string) => item)
}
.width('100%')
}
.scrollable(ScrollDirection.Vertical) // 滚动方向纵向
.scrollBar(BarState.On) // 滚动条常驻显示
.scrollBarColor(Color.Gray) // 滚动条颜色
.scrollBarWidth(10) // 滚动条宽度
.friction(0.6)
.edgeEffect(EdgeEffect.None)
.onScrollStop(() => {
let contentHeight = this.screenHeight
let currentIndex = (this.scroller.currentOffset().yOffset+contentHeight)/160
console.info('当前是第' + Math.ceil(currentIndex) + '个item')
})
}.width('100%').height('100%').backgroundColor(0xDCDCDC)
}
}
可以通过以下方法获取到每个item的高度,
.onAreaChange((oldValue: Area, newValue: Area) => {
console.info(`Ace: on area change, oldValue is ${newValue.height}`)
let ss = newValue.height
})
可使用onVisibleAreaChange方法,获取到组件的可见回调,具体请参考:华为开发者联盟
更多关于如何知道Scroll组件目前显示到最后一个item的角标(HarmonyOS 鸿蒙Next)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
实现思路
- 监听滚动事件:借助
Scroll
组件提供的滚动事件监听器,在滚动过程中实时获取滚动位置信息。 - 计算可视区域:结合组件的尺寸、每个
item
的尺寸以及滚动位置,算出当前可视区域。 - 确定最后一个
item
的角标:依据可视区域的范围,确定最后显示的item
的角标。
// 计算最后一个可见项的索引
calculateLastVisibleIndex(scrollOffset: number) {
const itemHeight = 50
const containerHeight = 300
const visibleStart = Math.floor(scrollOffset / itemHeight)
const visibleEnd = visibleStart + Math.floor(containerHeight / itemHeight)
this.lastVisibleIndex = Math.min(visibleEnd, this.itemList.length - 1)
}
在HarmonyOS鸿蒙Next中,要获取Scroll组件当前显示的最后一个item的角标,可以通过监听Scroll组件的滑动事件来实现。具体步骤如下:
-
使用
onScroll
事件:Scroll
组件提供了onScroll
事件,该事件会在用户滑动时触发,返回当前滑动的偏移量。 -
计算最后一个item的角标:根据滑动的偏移量,结合每个item的高度或宽度,可以计算出当前显示的最后一个item的角标。
示例代码如下:
Scroll({ scrollable: ScrollDirection.Vertical }) {
// 你的Item列表
}
.onScroll((xOffset: number, yOffset: number) => {
const itemHeight = 100; // 假设每个item的高度为100
const lastVisibleItemIndex = Math.floor(yOffset / itemHeight) + Math.floor(viewportHeight / itemHeight);
console.log("最后一个可见item的角标:", lastVisibleItemIndex);
})