目录

通过外接键盘无法输入数字

问题现象

用户通过外接键盘输入验证码时无法输入数字,但是英文字母可以正常输入。

背景知识

问题定位

  1. 用UIViewer检查验证码输入框组件,发现是用的Text组件,该组件聚焦无法自动拉起输入法,需应用自行绑定输入法。
  2. 搜索inputMethod.getController,检查应用是否绑定输入法,检查代码逻辑,验证码输入逻辑如下。
    this.inputController.on('insertText', (text) => {
      this.verifyCode += text;
    })
  3. 其他键盘按键能通过上述方法监听到,然而数字按键无法监听到,输出如下日志,即输入法会忽略数字按键,数字按键的上屏不由输入法控制。
    isConsumedKeyDown. ignore keyCodeNumber.
  4. 检查是否实现onKeyPreIme或onKeyEvent监听数字按键。

分析结论

由于数字按键的上屏不由输入法控制,而且应用又没有通过onKeyPreIme或onKeyEvent监听数字按键,所以无法通过数字按键输入验证码。

修改建议

import inputMethod from '@ohos.inputMethod';
import { KeyCode } from '@ohos.multimodalInput.keyCode';

@Entry
@Component
struct KeyboardTestPage {
  @State inputText: string = ''; // inputText作为Text组件要显示的内容。
  private isAttach: boolean = false;
  private inputController: inputMethod.InputMethodController = inputMethod.getController();

  build() {
    Column() {
      Text(this.inputText) // Text组件作为自绘编辑框的文本显示组件。
        .fontSize(16)
        .width('100%')
        .lineHeight(25)
        .id('customInput')
        .onBlur(() => {
          this.off();
        })
        .height(50)
        .border({ color: '#554455', radius: 30, width: 1 })
        .maxLines(1)
        .onClick(() => {
          this.attachAndListener(); // 点击控件
        })
        .onKeyEvent((event: KeyEvent) => {
          this.handleKeyEvent(event);
        })
        .margin({top: 200})
        .focusable(true)
        .defaultFocus(true)
    }
    .height('100%')
    .width('100%')
  }

  async attachAndListener() { // 绑定和设置监听
    focusControl.requestFocus('customInput');
    try {
      await this.inputController.attach(true, {
        inputAttribute: {
          textInputType: inputMethod.TextInputType.TEXT,
          enterKeyType: inputMethod.EnterKeyType.SEARCH
        }
      });
    } catch (err) {
      console.error(`Failed to attach: code:${err.code}, message:${err.message}`);
    }
    if (!this.isAttach) {
      this.inputController.on('insertText', (text) => {
        this.inputText += text;
      });
      this.inputController.on('deleteLeft', (length) => {
        this.inputText = this.inputText.substring(0, this.inputText.length - length);
      });
      this.isAttach = true;
    }
  }

  off() {
    this.isAttach = false;
    this.inputController.off('insertText');
    this.inputController.off('deleteLeft');
  }

  handleKeyEvent(event: KeyEvent) {
    if (event.type === KeyType.Down) {
      return;
    }
    if (event.keyCode >= KeyCode.KEYCODE_0 && event.keyCode <= KeyCode.KEYCODE_9) {
      this.inputText += (event.keyCode - KeyCode.KEYCODE_0);
    }
  }
}