目录

滚动组件是否支持滚动时隐藏键盘

问题现象

List组件里面嵌套TextInput组件,如何实现滚动时隐藏键盘的效果?

效果预览

背景知识

解决方案

通过设置focusable的属性值来控制键盘的显示和隐藏,当List组件开始滚动时,设置focusable的属性值为false隐藏键盘。当List组件停止滚动时,设置focusable的属性值为true点击时显示键盘。

@Entry
@Component
struct ListExampleDemo {
  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
  controller: TextInputController = new TextInputController();
  @State isFocusable: boolean = true;

  build() {
    Column() {
      List({ space: 20, initialIndex: 0 }) {
        ForEach(this.arr, (item: number) => {
          ListItem() {

            TextInput({ text: item + '', controller: this.controller })
              .fontSize(16)
              .backgroundColor(0xFFFFFF)
              .focusable(this.isFocusable)
              .onClick(() => {
                this.isFocusable = true;
              });
          };
        }, (item: string) => item);
      }
      .listDirection(Axis.Vertical) // 排列方向
      .scrollBar(BarState.Off)
      .friction(0.6)
      .edgeEffect(EdgeEffect.Spring) // 边缘效果设置为Spring
      .onScrollStart(() => {
        // List组件开始滚动时,将focusable设置为false
        this.isFocusable = false;
      })
      .onScrollStop(() => {
        // List组件停止滚动时,将focusable设置为true
        this.isFocusable = true;
      })
      .width('90%');
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#f1f3f5')
    .padding({ top: 5 });
  }
}