HarmonyOS list的scrollToIndex方法?

在我们的APP中,有使用List组件做了一个横向的温度选择器,有18到32度可选择,我有个按钮,可以一键选择

问题:

//如果一键选择32度,使用scrollToIndex(14)可以自动滚动到最后
.onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => {
  firstIndex= 12
  lastIndex=14
  centerIndex=14
})
 //如果一键选择18度,使用scrollToIndex(0)却只能滚动到第3行
.onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => {
  firstIndex= 0
  lastIndex=4
  centerIndex=2
})

按理来说,我使用scrollToIndex(0)之后centerIndex应该是0才对

阅读 479
1 个回答

centerIndex是List显示区域内中间位置子组件的索引值。

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-container-list-V5\#onscrollindex

// xxx.ets
@Entry
@Component
struct ListExample {
  private arr: number[] = []
  private scrollerForList: Scroller = new Scroller()

  aboutToAppear() {
    for (let i = 0; i < 20; i++) {
      this.arr.push(i)
    }
  }
  build() {
    Column() {
      Row() {
        List({ space: 1, initialIndex: 0, scroller: this.scrollerForList }) {
          ForEach(this.arr, (item: number) => {
            ListItem() {
              Text('' + item)
                .width(50).height(100).fontSize(16)
                .textAlign(TextAlign.Center)
            }
            .borderRadius(10).backgroundColor(0xFFFFFF)
          }, (item: number) => JSON.stringify(item))
        }
        .chainAnimation(true)
        .edgeEffect(EdgeEffect.Spring)
        .listDirection(Axis.Horizontal)
        .borderRadius(10)
        .backgroundColor(0xDCDCDC)
        // .onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => {
        //   firstIndex= 12
        //   lastIndex=14
        //   centerIndex=14
        // })
        .onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => {
          console.info('first' + firstIndex)
          console.info('last' + lastIndex)
          console.info('center' + centerIndex)
          firstIndex= 0
          lastIndex=4
          centerIndex=2
          console.info('-------')
          console.info('first' + firstIndex)
          console.info('last' + lastIndex)
          console.info('center' + centerIndex)
          console.info('++++++++++++++++++++++')
        })
      }
      .width('100%')
      .height(100)
      .backgroundColor(0xDCDCDC)
      Button() { Text('scrollToIndex (0)') }.onClick(()=>{
        this.scrollerForList.scrollToIndex(0,true)
      }).height('10%').width('60%')
      Button() { Text('scrollToIndex (19)') }.onClick(()=>{
        this.scrollerForList.scrollToIndex(19,true)
      }).height('10%').width('60%')
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进