import { promptAction } from '@kit.ArkUI';

@Entry
@Component
struct ListTestDemo {
  private listScroller: ListScroller = new ListScroller();
  @State showBakTopButton: boolean = false;

  build() {
    Column() {
      List({ scroller: this.listScroller }) {
        ForEach(new Array<number>(50).fill(0), (item: string, index: number) => {
          ListItem() {
            Text((item + index).toString())
              .width(50)
              .height(50)
              .margin(4)
              .backgroundColor(Color.Orange)
              .textAlign(TextAlign.Center)
          }
        })
      }
      .width('100%')
      .height(200)
      .lanes(2)
      .alignListItem(ListItemAlign.Center)
      .backgroundColor(Color.Pink)
      .listDirection(Axis.Horizontal)
      .scrollBar(BarState.Off)
      .edgeEffect(EdgeEffect.Fade)
      .onReachEnd(() => {
        promptAction.showToast({ message: '到底啦', duration: 2000 })
      })
      .onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => {
        if (centerIndex > 20) {
          this.showBakTopButton = true;
        }
        if (firstIndex === 0) {
          this.showBakTopButton = false;
        }
        promptAction.showToast({
          message: `firstIndex: ${firstIndex}, lastIndex: ${lastIndex}, centerIndex: ${centerIndex}`, duration: 2000
        })
      })

      if (this.showBakTopButton) {
        Button('回到顶部')
          .width(200)
          .onClick(() => {
            // 回到顶部方法1:
            this.listScroller.scrollTo({
              xOffset: 0,
              yOffset: 0,
              animation: { duration: 2000 }
            })
            // 回到顶部方法2:
            // this.listScroller.scrollToIndex(0, true);
          })
      }
    }
    .height('100%')
    .width('100%')
    .backgroundColor(Color.Yellow)
  }
}

在这里插入图片描述

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐