目录

如何根据单行Item数量动态调整布局

问题现象

如何使用Grid组件实现布局只有一行,宽度固定,横向排列,当Item数量小于5时,Item宽度按照数量均分,当Item数量大于5时指定宽度且横向可以滚动的效果?

效果预览

背景知识

解决方案

获取当前屏幕的宽度,当Item数量大于5时,Item宽度指定为100vp,当Item数量小于5时,动态设置Item宽度。

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

@Entry
@Component
struct HorizontalIndex {
  @State screenWidth: number = 0;
  @State arr: Array<number> = [0, 1, 2, 3, 4, 5, 6, 7];

  aboutToAppear(): void {
    // 使用display.getDefaultDisplaySync()方法获取当前屏幕宽度
    this.screenWidth = this.getUIContext().px2vp(display.getDefaultDisplaySync().width);
  }

  getItemWidth(): number {
    // 当Item数量大于5时,宽度指定为100
    if (this.arr.length > 5) {
      return 100;
    } else {
      // 当Item数量小于5时,Item宽度按照数量均分
      return (this.screenWidth - (this.arr.length - 1) * 10) / this.arr.length;
    }
  }

  build() {
    Column() {
      Grid() {
        ForEach(this.arr, (num: number) => {
          GridItem() {
            Column() {
              Text(`${num}`)
                .fontColor(Color.White);
            }
            .justifyContent(FlexAlign.Center)
            .alignItems(HorizontalAlign.Center)
            .backgroundColor(Color.Blue)
            .width(this.getItemWidth())
            .height(100);
          };
        });
      }
      // 设置当前网格布局行的数量为1
      .rowsTemplate('1fr')
      .height(100)
      // 设置列与列的间距为10
      .columnsGap(10)
      .width('100%')
      .backgroundColor('#fafafa');

      Button('数量改变')
        .margin({ top: 20 })
        .onClick(() => {
          this.arr = [0, 1, 2, 3,];
        });
    }
    .width('100%')
    .height('100%');
  }
}