目录

List组件实现自定义时间选择器

问题现象

目前HarmonyOS官方提供的TextPicker组件没有横向滑动的能力,怎样实现横向滑动的时间选择器?

效果预览

背景知识

序号

名称

说明

1

Vertical

方向为纵向。

2

Horizontal

方向为横向。

解决方案

由于TextPicker组件没有横向滑动的能力,因此可以采用List滑动组件,实现横向滚动的时间选择器,采用scrollSnapAlign属性使List中间项对齐,同时将中间的Item差异化处理来进行突出显示。

@Entry
@Component
struct ListCustomTimePicker {
  private arr: string[] = ['5', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55', '60'];
  @State centerIndex: number = 0;

  build() {
    Row() {
      List() {
        ForEach(this.arr, (item: number, index: number) => {
          ListItem() {
            Row() {
              Text('' + item)
                // 判断语句,当索引位置在显示的中间时,对该时间放大处理
                .fontSize(index === this.centerIndex ? 30 : 18)
                .fontColor(index === this.centerIndex ? Color.Black : Color.Gray)
                .textAlign(TextAlign.Center);
            }
            .width('20%') // 单行显示5个item
            .height(50)
            .justifyContent(FlexAlign.Center);
          };
        }, (item: string) => item);
      }
      .scrollSnapAlign(ScrollSnapAlign.CENTER) // 中间项对齐
      .listDirection(Axis.Horizontal) // List组件设置横向滚动
      .scrollBar(BarState.Off)
      .onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => {
        // 获取屏幕中间item的索引值
        this.centerIndex = centerIndex;
        console.info(`firstIndex:${firstIndex},lastIndex:${lastIndex}`);
      })
      .width('100%');
    }
    .width('100%')
    .height(50)
    .backgroundColor(0xDCDCDC);
  }
}