基于自定义键盘设置光标位置

基于自定义键盘设置光标位置

HarmonyOS
2024-07-22 12:33:20
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
pfuchenlu
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 }) 
  } 
}
分享
微博
QQ
微信
回复
2024-07-23 18:29:19
相关问题
如何设置自定义弹窗位置
1661浏览 • 1回复 待解决
HarmonyOS TextInput自定义键盘问题
88浏览 • 1回复 待解决
HarmonyOS TextInput绑定自定义键盘问题
93浏览 • 1回复 待解决
设置TextInput组件光标位置在起点
103浏览 • 1回复 待解决
HarmonyOS 如何设置自定义字体
223浏览 • 1回复 待解决
自定义弹窗自定义转场动画
634浏览 • 1回复 待解决
如何设置自定义组件height缺省
1538浏览 • 1回复 待解决
如何自定义拼接设置UserAgent参数
1867浏览 • 3回复 待解决