你可以使用 focusControl.requestFocus 对需要获取焦点的组件设置焦点,具体可以参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-refere...示例代码如下:@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获焦 }) } } }本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。
你可以使用 focusControl.requestFocus 对需要获取焦点的组件设置焦点,具体可以参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-refere...示例代码如下:
本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。