输入法框架提供了InputMethodController实例,通过getController可获取到,使用 InputMethodController实例可以绑定输入法,监听输入法应用的插入、删除、选择、光标移动等操作,从而实现一个自绘编辑框。
开发步骤
1.开发者在实现一个自绘编辑框控件时,需要在在DevEco Studio工程中新建一个ets文件,命名为自定义控件的名称,本示例中命名为CustomInput,在文件中定义一个自定义控件,并从@kit.IMEKit中导入inputMethod。
import { inputMethod } from '@kit.IMEKit';
@Component
export struct CustomInput {
build() {
}
}
2.在控件中,使用Text组件作为自会编辑框的文本显示组件,使用状态变量inputText作为Text组件要显示的内容。
import { inputMethod } from '@kit.IMEKit';
@Component
export struct CustomInput {
@State inputText: string = ''; // inputText作为Text组件要显示的内容。
build() {
Text(this.inputText) // Text组件作为自会编辑框的文本显示组件。
.fontSize(16)
.width('100%')
.lineHeight(40)
.id('customInput')
.height(45)
.border({ color: '#554455', radius: 30, width: 1 })
.maxLines(1)
}
}
3.在控件中获取inputMethodController实例,并在文本点击时调用controller示例的attach方法绑定和拉起软键盘,并注册监听输入法插入文本、删除等方法,本示例仅展示插入、删除。
import { inputMethod } from '@kit.IMEKit';
@Component
export struct CustomInput {
@State inputText: string = ''; // inputText作为Text组件要显示的内容。
private inputController: inputMethod.InputMethodController = inputMethod.getController();
build() {
Text(this.inputText) // Text组件作为自会编辑框的文本显示组件。
.fontSize(16)
.width('100%')
.lineHeight(40)
.id('customInput')
.height(45)
.border({ color: '#554455', radius: 30, width: 1 })
.maxLines(1)
.onClick(()=>{
this.attachAndListener(); // 点击控件
})
}
async attachAndListener() { // 绑定和设置监听
focusControl.requestFocus('CustomInput');
await this.inputController.attach(true, {
inputAttribute: {
textInputType: inputMethod.TextInputType.TEXT,
enterKeyType: inputMethod.EnterKeyType.SEARCH
}
});
this.inputController.on('insertText', (text) => {
this.inputText += text;
})
this.inputController.on('deleteLeft', (length) => {
this.inputText = this.inputText.substring(0, this.inputText.length - length);
})
}
}
4.在应用界面布局中引入该控件即可,此处假设使用界面为Index.ets和控件CustomInput.ets在同一目录下。
import { CustomInput } from './CustomInput'; // 导入控件
@Entry
@Component
struct Index {
build() {
Column() {
CustomInput() // 使用控件
}
}
}
如果大家还没有掌握鸿蒙,现在想要在最短的时间里吃透它,我这边特意整理了《鸿蒙语法ArkTS、TypeScript、ArkUI、教学视频》以及《鸿蒙生态应用开发白皮书V2.0PDF》《鸿蒙开发学习手册》(共计890页)鸿蒙开发资料等…希望对大家有所帮助:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
鸿蒙语法ArkTS、TypeScript、ArkUI等…视频教程:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
OpenHarmony APP开发教程步骤:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
鸿蒙生态应用开发白皮书V2.0PDF:https://docs.qq.com/doc/DZVVkRGRUd3pHSnFG
南北双向高工技能基础:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
应用开发中高级就业技术:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
全网首发-工业级 南向设备开发就业技术:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
《鸿蒙开发学习手册》:
如何快速入门:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
1.基本概念
2.构建第一个ArkTS应用
3.……
开发基础知识:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
1.应用基础知识
2.配置文件
3.应用数据管理
4.应用安全管理
5.应用隐私保护
6.三方应用调用管控机制
7.资源分类与访问
8.学习ArkTS语言
9.……
基于ArkTS 开发:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
1.Ability开发
2.UI开发
3.公共事件与通知
4.窗口管理
5.媒体
6.安全
7.网络与链接
8.电话服务
9.数据管理
10.后台任务(Background Task)管理
11.设备管理
12.设备使用信息统计
13.DFX
14.国际化开发
15.折叠屏系列
16.……