HarmonyOS TextArea如何自动获取焦点弹出键盘?

如题:HarmonyOS TextArea如何自动获取焦点弹出键盘?

阅读 576
1 个回答

可以使用 focusControl.requestFocus 对需要获取焦点的组件设置焦点,绑定自定义键盘

具体可以参考文档: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-attributes-focus-V5\#requestfocus9

参考demo:

@Entry
@Component
struct TextInputExample {
  controller: TextInputController = new TextInputController()
  @State inputValue: string = ""
  ep: number = 0;
  del:boolean = false; // 自定义键盘组件 
  @Builder CustomKeyboardBuilder() {
    Column() {
      Button('关闭键盘').onClick(() => { // 关闭自定义键盘 
        this.controller.stopEditing() })
      Button('删除字符').onClick(() => {
        this.inputValue = this.inputValue.substring(0, this.ep-1) + this.inputValue.substring(this.ep)
        this.del = true })
      Grid() {
        ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => {
          GridItem() {
            Button(item + "")
              .width(110)
              .onClick(() => {
                this.inputValue = this.inputValue.substring(0, this.ep) + item + this.inputValue.substring(this.ep)
                this.del = false })
          }
        }
      }) }
    .maxCount(3)
    .columnsGap(10)
    .rowsGap(10)
    .padding(5)
  }
  .backgroundColor(Color.Gray)
}
build() {
  Column() {
    TextInput({
      controller: this.controller, text: this.inputValue
    })
  } // 绑定自定义键盘 
  .customKeyboard(this.CustomKeyboardBuilder())
  .margin(10)
  .id('input1') //为组件设置id,
  .border({ width: 1 }) //用于感知光标的变化,然后调整光标位置 
  .onChange(() => {
    if(this.del){
      this.controller.caretPosition(--this.ep)
    }else{
      this.controller.caretPosition(++this.ep)
    }
  })
  .onTextSelectionChange((ss) => { this.ep = ss; })
  Button("触发主动获焦")
    .width(200)
    .height(70)
    .fontColor(Color.White)
    .onClick(() => {
      focusControl.requestFocus('input1') // 使TextInput获焦
    })
}
}
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进