接口 | 描述 |
|---|---|
attach | 自绘控件绑定输入法。 |
detach | 自绘控件解除与输入法的绑定。 |
on('insertText') | 订阅输入法应用插入文本事件。 |
on('deleteLeft') | 订阅输入法应用向左删除事件。 |

this.inputController.on('insertText', (text) => {
this.verifyCode += text;
}) isConsumedKeyDown. ignore keyCodeNumber.
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);
}
}
}