中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
基于自定义键盘设置光标位置
微信扫码分享
class MyKeyboardController { public onInputChanged?: (value: string) => void public inputController = new TextInputController() public carePosition = -1 private inputValue = '' onKeyClicked(key: string) { const index = this.inputController.getCaretOffset().index if (key === 'A' || key === 'B') { this.setInputValue(this.inputValue.substring(0, index) + key + this.inputValue.substring(index)) this.carePosition = index + 1 } else if (key === '<') { if (index > 0) { this.setInputValue(this.inputValue.substring(0, index - 1) + this.inputValue.substring(index)) this.carePosition = index - 1 } } } setInputValue(value: string) { if (this.carePosition >= 0) { this.inputController.caretPosition(this.carePosition) this.carePosition = -1 } if (this.inputValue === value) { return; } this.inputValue = value if (this.onInputChanged) { this.onInputChanged(value) } } } @Component struct MyKeyboardA { controller?: MyKeyboardController private keys = ['A', 'B', '<'] build() { Row() { ForEach(this.keys, (v: string) => { Text(v) .layoutWeight(1) .height(44) .borderWidth(1) .borderColor(Color.Gray) .borderRadius(4) .onClick(() => { this.controller?.onKeyClicked(v) }) }) } .height(300) .backgroundColor(Color.Gray) } } @Entry @Component export struct RichKeyPage { keyboardController = new MyKeyboardController() @State text: string = '' aboutToAppear(): void { this.keyboardController.onInputChanged = (value) => { this.text = value } } build() { Column({ space: 20 }) { TextInput({ text: this.text, controller: this.keyboardController.inputController }) .width('100%') .height(44) .customKeyboard(this.myKeyboardA()) .onChange((value) => { this.keyboardController.setInputValue(value) }) Button('点击直接更改输入框内容') .width('100%') .height(44) .onClick(() => { this.text = '12345678' }) } } @Builder myKeyboardA() { MyKeyboardA({ controller: this.keyboardController }) } }