【关键字】
TextInput / 监听键盘事件 / 软键盘输入
【问题描述】
问题一:
没有外接键盘 就是系统的软键盘输入 可以监听使用的按了哪个按键吗?
问题二:
情景是有多个输入框 输入框内按删除,当前输入框删完后,需要自动走到下一个输入框继续删除,中间也可以删除再重新输入。例如:输入验证码
问题三:
写一个键盘相关的util 需要控制键盘开启,可以只用context吗?还是一定要绑定TextInput?
【解决方案】
问题一:
系统的软键盘输入目前无法获取keyCode。如果只需要字母或者数字按键的话,可以截取onChange事件的value最后一个字符串来知道按了哪个键。
问题二:
解决验证码的问题。重点是控制输入法的绑定,解绑,订阅事件。
可以参考以下相关代码:
import { inputMethod } from '@kit.IMEKit';
import { Logger } from '../utils/Logger';
import { BusinessError } from '@kit.BasicServicesKit';
@Extend(Text)
function verifyCodeUnitStyle() {
.fontSize($r("sys.float.ohos_id_text_size_body1"))
.fontWeight(60)
.textAlign(TextAlign.Center)
.width(60)
.height('100%')
.margin({ left: 5, right: 5 })
.border({
width: { bottom: 1 },
color: { bottom: Color.Grey },
style: { bottom: BorderStyle.Solid }
})
}
@Entry
@Component
export struct VerifyCodeView {
build() {
Column() {
VerifyCodeComponentWithoutCursor()
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
}
}
@Component
struct VerifyCodeComponentWithoutCursor {
@State codeText: string = "";
@State focus: boolean = false
@State inputController: inputMethod.InputMethodController = inputMethod.getController();
private isAttached: boolean = false;
private verifyCodeLength: number = 6;
private codeIndexArray: Array<number> = Array.from([0, 1, 2, 3, 4, 5]);
needFocusKey: string = 'textinput'
onPageShow(): void {
this.focus = true
}
async setAttachAndListener() {
if (this.isAttached) {
return;
}
let textConfig: inputMethod.TextConfig = {
inputAttribute: {
textInputType: inputMethod.TextInputType.NUMBER,
enterKeyType: inputMethod.EnterKeyType.GO
},
};
await this.inputController.attach(true, textConfig);
this.isAttached = true;
this.attachListener();
}
@Builder
buildVerifyCodeComponent() {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
ForEach(this.codeIndexArray, (item: number, index: number) => {
Text(this.codeText[item])
.verifyCodeUnitStyle()
}, (item: number, index: number) => item.toString())
}
.backgroundColor(Color.Transparent)
.height(50)
.margin({ left: $r("sys.float.ohos_id_card_margin_start"), right: $r("sys.float.ohos_id_card_margin_start") })
.defaultFocus(this.focus)
.key(this.needFocusKey)
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
if (isVisible && currentRatio >= 1.0) {
this.setAttachAndListener()
}
if (!isVisible && currentRatio < 1.0) {
this.inputController.detach((err: BusinessError) => {
})
}
})
.onClick(() => {
this.focus = true
// TODO 知识点:点击本组件时弹出输入法
// this.inputController.showTextInput()
if (this.isAttached) {
this.inputController.showTextInput()
return
}
})
}
build() {
Row() {
this.buildVerifyCodeComponent()
}
}
}
问题三:
参考上面的代码,使用inputController控制键盘开启。