HarmonyOS的Search组件如何自定义键盘避让方式?

阅读 556
avatarAI BotBETA

在HarmonyOS中,自定义Search组件的键盘避让方式可以通过设置SoftInputMode属性来实现。以下是一个示例代码,展示了如何在XML布局文件中配置Search组件以自定义键盘避让方式:

### 解决方案

在XML布局文件中,为包含Search组件的页面或布局设置`SoftInputMode`属性。例如:

<DirectionalLayout

xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:width="match_parent"
ohos:height="match_parent"
ohos:orientation="vertical"
ohos:config_softInputMode="adjustResize"> <!-- 设置SoftInputMode为adjustResize -->

<!-- 其他布局元素 -->

<Search
    ohos:id="$+id:search_component"
    ohos:width="match_parent"
    ohos:height="wrap_content"
    ohos:hint="Search..." />

<!-- 其他布局元素,如列表等,用于显示搜索结果 -->

</DirectionalLayout>


在上述代码中,`ohos:config_softInputMode="adjustResize"`指示系统在键盘弹出时调整布局大小,以便为键盘腾出空间,同时确保Search组件和其他布局元素能够正确避让键盘。

### 解释

- `adjustResize`:此模式会使布局重新布局,以便为软键盘腾出空间。通常,这会导致包含输入字段的视图向上移动,以便用户可以看到输入字段和正在输入的内容。
- `adjustPan`:另一种模式,它会使整个布局平移,以便输入字段始终可见,但可能会导致部分布局内容被遮挡。
1 个回答

自定义键盘的避让功能。
开发者自己实现自定义键盘的避让功能
开发者需要监听自定义键盘根节点的onAreaChange生命周期,获取自定义键盘的高度,根据实际场景设置布局的避让。
监听自定义键盘布局的onAreaChange生命周期,通过newValue.height获取自定义键盘弹出时的高度,根据实际业务场景计算布局避让高度avoidHeight。

// entry/src/main/ets/view/CustomKeyboard.ets
@Component
export struct CustomKeyboard {
  // ...

  build() {
    Column() {
      // ...
    }
    .onAreaChange((oldValue: Area, newValue: Area) => {
      this.customKeyboardHeight = Number(newValue.height);
      let avoidHeight: number = (this.isCustomKeyboardAttach ? this.customKeyboardHeight : this.systemKeyboardHeight)
        - this.bottomRectHeight;
      this.keyBoardController.changeAvoidHeight(avoidHeight);
    })
    // ...
  }
}

通过emitter的方式,发送自定义键盘高度变化的通知。

// entry/src/main/ets/model/KeyboardController.ets
// 以公共事件的形式,通知布局高度变化
changeAvoidHeight(value: number) {
  let event: emitter.InnerEvent = {
    eventId: Constants.AVOID_EVENT_ID
  };
  let eventData: emitter.EventData = {
    data: {
      'avoidHeight': value
    }
  };
  emitter.emit(event, eventData);
}

接收到高度变化通知后,根据实际业务场景,设置页面的避让高度。

// entry/src/main/ets/pages/MainPage.ets
@Entry
@Component
struct MainPage {
  @State bottomPadding: number = Constants.MAIN_PAGE_INITIAL_PADDING;

  aboutToAppear(): void {
    let event: emitter.InnerEvent = {
      eventId: Constants.AVOID_EVENT_ID
    };
    emitter.on(event, (eventData: emitter.EventData) => {
      if (eventData.data) {
        let avoidHeight: number = eventData.data['avoidHeight'];
        if (avoidHeight === 0) {
          this.bottomPadding = Constants.MAIN_PAGE_INITIAL_PADDING;
        } else {
          this.bottomPadding = avoidHeight;
        }
      }
    });
  }

  build() {
    Navigation() {
      Column() {
        // ...
      }
      .padding({ bottom: this.bottomPadding })
      // ...
    }
    .mode(NavigationMode.Stack)
    .titleMode(NavigationTitleMode.Full)
    .title($r('app.string.main_page_title'))
  }
}

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进