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

HarmonyOS
2024-12-25 08:58:19
856浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
put_get

可以使用 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获焦
    })
}
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
分享
微博
QQ
微信
回复
2024-12-25 11:32:06


相关问题
HarmonyOS TextArea获取焦点
530浏览 • 1回复 待解决
HarmonyOS TextArea组件如何主动获取焦点
546浏览 • 1回复 待解决
HarmonyOS 键盘焦点不能自动上推屏幕
479浏览 • 1回复 待解决
HarmonyOS TextInput自动获取焦点问题
779浏览 • 1回复 待解决
HarmonyOS 输入框获取焦点后无法弹出
749浏览 • 1回复 待解决