本文原创发布在华为开发者社区。
介绍
本示例实现自定义键盘,有三种模式:数字输入模式、英文键盘和中文键盘。
效果预览
使用说明
- 默认隐藏键盘,点击输入栏显示键盘
键盘分为三个模式:数字输入模式、英文键盘和中文键盘。数字输入自定义了一些特殊输入如300,600等可快速输入前缀。
实现思路
- 绘制入口页面,默认键盘隐藏,需要时唤起
- 监听键盘状态,以及模式切换,显示不同键盘
- 自定义每个模式键盘,监听键盘事件。
键盘事件监听核心代码如下:
监听键盘输入状态,获取当前输入框中的字符,
//KeyEventListen.ets
onKeyboardMethod(action: string, content?: string): string {
if (action === CommonConstants.DELETE_CHARACTERS) {
if (this.isMultiSelect) {
this.inputContent = content.replace(content?.substring(this.notSelectionStart, this.notSelectionEnd), '');
this.cursorPosition = this.notSelectionStart;
} else if (content.length === this.selectionStart && content.length === this.selectionEnd) {
this.inputContent = content?.substring(0, content.length - 1);
this.cursorPosition = this.selectionEnd - 1;
} else if (this.selectionStart === this.selectionEnd && content.length > this.selectionEnd) {
this.inputContent = content.replace(content?.substring(this.selectionStart - 1, this.selectionEnd), '');
this.cursorPosition = this.selectionStart - 1;
}else{
this.inputContent = content;
}
}
} else if (action === CommonConstants.CLEAR_CHARACTERS) {
this.inputContent = '';
this.cursorPosition = 0;
} else if (this.inputContent.length >= CommonConstants.MAXIMUM_NUMBER_INPUTS) {
promptAction.showToast({
message: $r('app.string.search_box_prompt')
});
return this.inputContent;
} else if (action === CommonConstants.STRING_CHARACTERS && content !== undefined) {
if (this.isMultiSelect) {
let currentContent = this.inputContent;
currentContent = currentContent.replace(currentContent?.substring(this.notSelectionStart,
this.notSelectionEnd), '');
this.inputContent = currentContent.slice(0, this.notSelectionStart) +
content + currentContent.slice(this.notSelectionStart);
this.cursorPosition = this.notSelectionStart + content.length;
} else if (this.selectionStart === this.selectionEnd && this.selectionStart < this.inputContent.length) {
if (this.selectionStart === 0 && this.selectionEnd === 0) {
this.inputContent = content + this.inputContent;
this.cursorPosition = content.length;
} else {
this.inputContent = this.inputContent.slice(0, this.selectionStart) +
content + this.inputContent.slice(this.selectionStart);
this.cursorPosition = this.selectionStart + content.length;
}
} else {
this.inputContent += content;
this.cursorPosition = this.selectionEnd + content.length;
}
}
return this.inputContent;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。