
回复
在鸿蒙中开发自定义编辑框,关键在于通过InputMethodController
实现与输入法的深度交互。本文用最简代码带你掌握绑定、事件监听和独立编辑功能~
import { inputMethod } from '@ohos.ime';
// 获取控制器实例
private controller = inputMethod.getController();
// 绑定输入法并显示键盘
async bindIme() {
await this.controller.attach(true, {
inputAttribute: {
textInputType: inputMethod.TextInputType.TEXT, // 输入类型(文本/数字等)
enterKeyType: inputMethod.EnterKeyType.DONE // 回车键样式
}
});
this.controller.showKeyboard(); // 主动显示键盘
}
// 失去焦点时解绑
async unbindIme() {
await this.controller.detach();
this.controller.hideKeyboard();
}
// 初始化时绑定事件
this.controller.on('insertText', (text) => {
this.handleTextInsert(text); // 自定义文本处理逻辑
});
// 示例:限制输入长度为20字
private handleTextInsert(text: string) {
if (this.inputText.length < 20) {
this.inputText += text;
} else {
showToast('输入长度已达上限');
}
}
this.controller.on('deleteLeft', (length) => {
this.inputText = this.inputText.slice(0, -length); // 删除光标左侧字符
});
this.controller.on('keyEvent', (event) => {
if (event.keyCode === inputMethod.KeyCode.ENTER) {
this.onSubmit(); // 触发提交逻辑
}
});
// 移动光标到指定位置
this.controller.setCursorPosition(5); // 移动到第5个字符后
// 选中文本(从第3到第8个字符)
this.controller.setSelection(3, 8);
this.controller.on('insertText', (text) => {
if (!this.inputText.includes('@') && text === '@') {
this.inputText += 'example.com'; // 自动补全域名
this.controller.setCursorPosition(this.inputText.length); // 光标移至末尾
}
});
// 点击编辑框时显示自定义键盘
@Entry
@Component
struct CustomInput {
@State inputText = '';
build() {
Column() {
TextInput(this.inputText)
.onClick(() => {
this.bindIme(); // 绑定输入法并显示键盘
})
}
}
}
import { inputMethod } from '@ohos.ime';
@Component
struct CustomEditText {
@State text = '';
private controller = inputMethod.getController();
// 生命周期:创建时绑定事件
aboutToAppear() {
this.initIme();
}
private initIme() {
this.controller.on('insertText', (t) => this.text += t);
this.controller.on('deleteLeft', () => this.text = this.text.slice(0, -1));
}
build() {
Row() {
// 自定义编辑框样式
Text(this.text)
.padding(8)
.border({ width: 1, color: '#D0D0D0' })
.cornerRadius(4)
.onClick(() => this.controller.showKeyboard()) // 点击唤起键盘
Button('清空')
.margin(8)
.onClick(() => {
this.text = '';
this.controller.deleteSurroundingText(this.text.length, 0); // 同步删除输入法缓存
})
}
}
}
// 根据输入类型显示不同键盘(如数字键盘)
async bindIme(type: inputMethod.TextInputType) {
await this.controller.attach(true, {
inputAttribute: { textInputType: type }
});
}
// 使用示例:电话号码输入
this.bindIme(inputMethod.TextInputType.PHONE);
private isAttached = false;
async attachSafely() {
if (!this.isAttached) {
await this.controller.attach(true);
this.isAttached = true;
}
}
attach()
建立输入法连接