TextInput组件支持输入任意文字内容,某些场景下,为了提升用户体验并确保输入的准确性和效率,需要针对不同场景弹出特定类型的软键盘。如纯数字输入框仅需要弹出数字软键盘、电话号码输入框需要支持'-','#'、邮箱输入框需要键盘提示常用邮箱后缀等场景。
@Entry
@Component
struct TextInputSoftKeyboard {
controller: TextInputController = new TextInputController();
@State inputValue: string = '';
// 自定义键盘组件
@Builder
CustomKeyboardBuilder() {
Column() {
Row() {
Row()
.width(18);
Row() {
// 图片资源需伙伴自行更改相似向下箭头图标
Image($r('app.media.under'))
.width(15)
.fillColor('#000');
}
.justifyContent(FlexAlign.Center)
.width(20)
.height(18)
.margin(10)
.borderRadius(10)
.onClick(() => {
// 点击关闭软键盘
this.controller.stopEditing();
});
}
.padding({ left: 24, right: 24 })
.width('100%')
.justifyContent(FlexAlign.SpaceBetween);
Grid() {
ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#', '.', '+', '-'], (item: number | string) => {
GridItem() {
Button(item + '')
.backgroundColor('#eaeaeb')
.width(110)
.fontColor('#000')
.onClick(() => {
this.inputValue += item;
});
};
});
}
.height('35%')
.padding(10)
.maxCount(3)
.columnsGap(10)
.rowsGap(10)
.padding(5);
}.backgroundColor('#d2d3d5');
}
build() {
Column() {
TextInput({ controller: this.controller, text: this.inputValue }) // 添加key属性让焦点转移到指定组件上
.customKeyboard(this.CustomKeyboardBuilder())
.margin(10);
}
.padding(16);
}
} Q:想做出TextInput限制输入两位小数,再输入则不再显示的效果。使用自定义键盘设置TextInput的inputFilter,自定义键盘输入三位小数后,onChange回调返回值为空,如何修改?
A:可以在onChange中使用toFixed方法将浮点数格式化为保留两位小数的字符串后返回结果。
Q:TextInput如何在初始状态只获取焦点不拉起键盘?
A:通过enableKeyboardOnFocus和defaultFocus属性将TextInput设置为当前页面的默认焦点且不显示输入键盘。