HarmonyOS鸿蒙Next中短信校验码控件软键盘的问题

HarmonyOS鸿蒙Next中短信校验码控件软键盘的问题 短信校验码控件进入页面后,会弹出来软键盘,然后软键盘又突然消息。

我们的期望: 短信校验码控件进入页面后,会弹出来软键盘,键盘不会消失。

我们的调用方法:

router.pushUrl({ url: 'pages/TextInputPage' },router.RouterMode.Standard,(err) => {
 if (err) {
   console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);
   return;
 }
 console.info('Invoke pushUrl succeeded.');
})

我们短信校验码控件的代码如下:

import inputMethod from '@ohos.inputMethod';
import { BusinessError } from '@ohos.base';

@Entry
@Component
export struct TextInputPage {
  @State codeTxt: string = '';
  @State screenWidth: number = 0;
  private inputController: inputMethod.InputMethodController = inputMethod.getController();
  private isAttached: boolean = false;
  private keyboardStatus: number = 0; // 默认是none, 1是hide,2是show

  aboutToAppear(): void {
    console.info('ImsaKit aboutToAppear')
    this.screenWidth = 1080;
  }

  onPageShow(): void {}

  @Builder componentBuilder() {
    Column() {
      Blank().height(42)
      this.buildTitleName()
      Blank().height(38)
      this.buildNumTip()
      this.buildAEnterCodeInput()
      Blank().height(20)
    }
    .margin({ top: 10 })
    .borderRadius(8)
    .backgroundColor(Color.White)
  }

  @Builder buildTitleName() {
    Row() {
      Text() {
        Span('输入验证码')
        .fontSize(18)
        .fontWeight(600)
        .fontColor(Color.Black)
      }
    }
    .width('100%')
    .justifyContent(FlexAlign.Start)
    .padding({ left: 20, right: 20 })
  }

  @Builder buildNumTip() {
    Row() {
      Text() {
        Span('已发送至')
        .fontSize(12)
        .fontWeight(400)
        .fontColor(Color.Grey)
      }
      Blank().width(5)
      Text() {
        Span("182XXXXX055")
        .fontSize(12)
        .fontWeight(500)
        .fontColor(Color.Black)
      }
    }
    .width('100%')
    .justifyContent(FlexAlign.Start)
    .padding({ left: 20, right: 20 })
  }

  @Styles fancyUse(){
    .width((this.screenWidth - 110) / 6)
    .height("100%")
    .margin({ left: 5, right: 5 })
    .border({ width: { bottom: 0.5 }, color: { bottom: Color.Grey }, style: { bottom: BorderStyle.Solid } })
  }

  @Builder buildAEnterCodeInput() {
    Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
      Text(this.codeTxt[0])
      .fontSize(18)
      .fontWeight(600)
      .textAlign(TextAlign.Center)
      .fancyUse()
      Text(this.codeTxt[1])
      .fontSize(18)
      .fontWeight(600)
      .textAlign(TextAlign.Center)
      .fancyUse()
      Text(this.codeTxt[2])
      .fontSize(18)
      .fontWeight(600)
      .textAlign(TextAlign.Center)
      .fancyUse()
      Text(this.codeTxt[3])
      .fontSize(18)
      .fontWeight(600)
      .textAlign(TextAlign.Center)
      .fancyUse()
      Text(this.codeTxt[4])
      .fontSize(18)
      .fontWeight(600)
      .textAlign(TextAlign.Center)
      .fancyUse()
      Text(this.codeTxt[5])
      .fontSize(18)
      .fontWeight(600)
      .textAlign(TextAlign.Center)
      .fancyUse()
    }
    .backgroundColor(Color.White)
    .height(50)
    .margin({ left: 15, right: 15 })
    .id("customInput")
    .defaultFocus(true)
    .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
      console.info('ImsaKit Test Text isVisible: ' + isVisible + ', currentRatio:' + currentRatio)
      if (isVisible && currentRatio >= 1.0) {
        console.info('ImsaKit Test Text is fully visible. currentRatio:' + currentRatio)
        if(!this.isAttached){
          this.attachAndListener();
        } else {
          console.info('in focus')
          focusControl.requestFocus('customInput')
        }
      }

      if (!isVisible && currentRatio <= 0.0) {
        console.info('ImsaKit Test Text is completely invisible.')
        // this.dettach()
      }
    })
    .onClick(async () => {
      console.info('ImsaKit keyboardStatus =' + this.keyboardStatus)
      if (this.isAttached && this.keyboardStatus != 2) {
        // 输入法配置项
        let textConfig: inputMethod.TextConfig = {
          inputAttribute: {
            textInputType: inputMethod.TextInputType.NUMBER,
            enterKeyType: inputMethod.EnterKeyType.GO
          };
        };

        // 控件绑定输入法
        await this.inputController.attach(true, textConfig)
        return
      }
    })
  }

  dettach() {
    this.inputController.off('insertText');
    this.inputController.off('deleteLeft');
    this.inputController.off('sendKeyboardStatus');
    this.inputController.detach((err: BusinessError) => {
      if (err) {
        console.error(`Failed to detach: ${JSON.stringify(err)}`)
        return
      }
      this.isAttached = false
      console.log('Succeeded in detaching inputMethod.')
    });
  }

  // 绑定和设置监听
  async attachAndListener() {
    // 输入法配置项
    let textConfig: inputMethod.TextConfig = {
      inputAttribute: {
        textInputType: inputMethod.TextInputType.NUMBER,
        enterKeyType: inputMethod.EnterKeyType.GO
      };
    };

    // 控件绑定输入法
    await this.inputController.attach(true, textConfig)
    console.info('come in')

    this.isAttached = true
    this.attachListener()
    console.info('attach succeed')
  }

  /**
   * 订阅输入法回调
   */
  attachListener(): void {
    // 订阅输入法应用插入文本事件
    this.inputController.on('insertText', (text) => {
      if (this.codeTxt.length >= 6) {
        return
      }
      this.codeTxt += text;
      console.info("this.inputText", "insertText this.inputText===" + this.codeTxt)
    })

    // 订阅输入法应用向左删除事件
    this.inputController.on('deleteLeft', (length) => {
      this.codeTxt = this.codeTxt.substring(0, this.codeTxt.length - length);
      console.info("this.inputText", "deleteLeft this.inputText===" + this.codeTxt)
    })

    // 订阅输入法应用发送输入法软键盘状态事件
    this.inputController.on('sendKeyboardStatus', (keyboardStatus: inputMethod.KeyboardStatus) => {
      this.keyboardStatus = keyboardStatus
      console.info("ImsaKit this.inputText keyboardStatus= " + this.keyboardStatus)
    })
  }

  build() {
    NavDestination() {
      Column() {
        this.componentBuilder()
      }
      .width('100%')
      .height('100%')
      .backgroundColor(Color.White)
      .padding({ left: 10, right: 10, bottom: 60 })
    }
    .hideTitleBar(false)
    .title("验证码")
    .size({ width: '100%', height: '100%' })
    .backgroundColor('#FFFFFF')
  }
}

更多关于HarmonyOS鸿蒙Next中短信校验码控件软键盘的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

当前所有的路由跳转推荐使用navigation,router已经不在演进

使用navigation跳转本地验证是符合您预期效果的

import { TextInputPage } from './TextInputPage'

@Entry
@Component
struct Index {
  @Provide('NavPathStack') pageInfos: NavPathStack = new NavPathStack()

  @Builder
  PageMap(name: string, param: Object) {
    if (name === 'TextInputPage') {
      TextInputPage()
    }
  }

  build() {
    Navigation(this.pageInfos) {
      Button('1232').onClick(() => {
        this.pageInfos.pushPathByName('TextInputPage', '')
      })
    }
    .hideTitleBar(true)
    .mode(NavigationMode.Stack)
    .navDestination(this.PageMap)
  }
}
import inputMethod from '@ohos.inputMethod';
import { BusinessError } from '@ohos.base';

@Entry
@Component
export struct TextInputPage {
  @State codeTxt: string = '';
  @State screenWidth: number = 0;
  private inputController: inputMethod.InputMethodController = inputMethod.getController();
  private isAttached: boolean = false;
  private keyboardStatus: number = 0; // 默认是none, 1是hide,2是show

  aboutToAppear(): void {
    console.info('ImsaKit aboutToAppear')
    this.screenWidth = 1080;
  }

  onPageShow(): void {}

  @Builder
  componentBuilder() {
    Column() {
      Blank().height(42)
      this.buildTitleName()
      Blank().height(38)
      this.buildNumTip()
      this.buildAEnterCodeInput()
      Blank().height(20)
    }
    .margin({ top: 10 })
    .borderRadius(8)
    .backgroundColor(Color.White)
  }

  @Builder
  buildTitleName() {
    Row() {
      Text() {
        Span('输入验证码')
          .fontSize(18)
          .fontWeight(600)
          .fontColor(Color.Black)
      }
    }.width('100%').justifyContent(FlexAlign.Start).padding({ left: 20, right: 20 })
  }

  @Builder
  buildNumTip() {
    Row() {
      Text() {
        Span('已发送至')
          .fontSize(12)
          .fontWeight(400)
          .fontColor(Color.Grey)
      }
      Blank().width(5)
      Text() {
        Span('182XXXXX055')
          .fontSize(12)
          .fontWeight(500)
          .fontColor(Color.Black)
      }
    }.width('100%').justifyContent(FlexAlign.Start).padding({ left: 20, right: 20 })
  }

  @Styles
  fancyUse(){
    .width((this.screenWidth - 110) / 6)
    .height("100%")
    .margin({ left: 5, right: 5 })
    .border({
      width: { bottom: 0.5 },
      color: { bottom: Color.Grey },
      style: { bottom: BorderStyle.Solid }
    })
  }

  @Builder
  buildAEnterCodeInput() {
    Flex({
      direction: FlexDirection.Row,
      alignItems: ItemAlign.Center,
      justifyContent: FlexAlign.SpaceBetween
    }) {
      Text(this.codeTxt[0])
        .fontSize(18)
        .fontWeight(600)
        .textAlign(TextAlign.Center)
        .fancyUse()
      Text(this.codeTxt[1])
        .fontSize(18)
        .fontWeight(600)
        .textAlign(TextAlign.Center)
        .fancyUse()
      Text(this.codeTxt[2])
        .fontSize(18)
        .fontWeight(600)
        .textAlign(TextAlign.Center)
        .fancyUse()
      Text(this.codeTxt[3])
        .fontSize(18)
        .fontWeight(600)
        .textAlign(TextAlign.Center)
        .fancyUse()
      Text(this.codeTxt[4])
        .fontSize(18)
        .fontWeight(600)
        .textAlign(TextAlign.Center)
        .fancyUse()
      Text(this.codeTxt[5])
        .fontSize(18)
        .fontWeight(600)
        .textAlign(TextAlign.Center)
        .fancyUse()
    }
    .backgroundColor(Color.White)
    .height(50)
    .margin({ left: 15, right: 15 })
    .id("customInput")
    .defaultFocus(true)
    .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
      console.info('ImsaKit Test Text isVisible: ' + isVisible + ', currentRatio:' + currentRatio)
      if (isVisible && currentRatio >= 1.0) {
        console.info('ImsaKit Test Text is fully visible. currentRatio:' + currentRatio)
        if(!this.isAttached){
          this.attachAndListener();
        }else{
          console.info('in focus')
          focusControl.requestFocus('customInput')
        }
      }
      if (!isVisible && currentRatio <= 0.0) {
        console.info('ImsaKit Test Text is completely invisible.')
      }
    })
    .onClick(async () => {
      console.info('ImsaKit keyboardStatus =' + this.keyboardStatus)
      if (this.isAttached && this.keyboardStatus != 2) {
        let textConfig: inputMethod.TextConfig = {
          inputAttribute: {
            textInputType: inputMethod.TextInputType.NUMBER,
            enterKeyType: inputMethod.EnterKeyType.GO
          }
        };
        await this.inputController.attach(true, textConfig)
        return
      }
    })
  }

  dettach() {
    this.inputController.off('insertText');
    this.inputController.off('deleteLeft');
    this.inputController.off('sendKeyboardStatus');
    this.inputController.detach((err: BusinessError) => {
      if (err) {
        console.error(`Failed to detach: ${JSON.stringify(err)}`);
        return;
      }
      this.isAttached = false
      console.log('Succeeded in detaching inputMethod.');
    });
  }

  async attachAndListener() {
    let textConfig: inputMethod.TextConfig = {
      inputAttribute: {
        textInputType: inputMethod.TextInputType.NUMBER,
        enterKeyType: inputMethod.EnterKeyType.GO
      }
    };
    await this.inputController.attach(true, textConfig)
    console.info('come in')
    this.isAttached = true
    this.attachListener()
    console.info('attach succeed')
  }

  attachListener(): void {
    this.inputController.on('insertText', (text) => {
      if (this.codeTxt.length >= 6) {
        return
      }
      this.codeTxt += text;
      console.info("this.inputText", "insertText this.inputText===" + this.codeTxt)
    })
    this.inputController.on('deleteLeft', (length) => {
      this.codeTxt = this.codeTxt.substring(0, this.codeTxt.length - length);
      console.info(this.inputText, `deleteLeft ${this.inputText}===` + this.codeTxt)
    })
    this.inputController.on('sendKeyboardStatus', (keyboardStatus: inputMethod.KeyboardStatus) => {
      this.keyboardStatus = keyboardStatus
      console.info(`ImsaKit ${this.inputText} keyboardStatus= ` + this.keyboardStatus)
    })
  }

  build() {
    NavDestination() {
      Column() {
        this.componentBuilder()
      }
      .width('100%')
      .height('100%')
      .backgroundColor(Color.White)
      .padding({
        left: 10,
        right: 10,
        bottom: 60
      })
    }
    .hideTitleBar(false)
    .title("验证码")
    .size({ width: '100%', height: '100%' })
    .backgroundColor('#FFFFFF')
  }
}

更多关于HarmonyOS鸿蒙Next中短信校验码控件软键盘的问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,短信校验码控件的软键盘问题主要涉及到输入法的交互和用户体验。鸿蒙Next的短信校验码控件通常会自动弹出数字键盘,以方便用户快速输入验证码。具体问题可能包括:软键盘未按预期弹出、键盘类型不正确(如弹出全键盘而非数字键盘)、输入焦点管理不当等。

在鸿蒙Next中,开发者可以通过InputMethodManager来控制软键盘的行为,例如通过showSoftInput方法显式请求软键盘显示,或通过hideSoftInput方法隐藏软键盘。此外,可以通过设置InputType属性来指定输入框的键盘类型,例如设置为InputType.TYPE_CLASS_NUMBER来确保弹出数字键盘。

如果遇到软键盘未按预期工作的情况,可以检查以下方面:控件的InputType是否正确设置、焦点管理是否合理、是否有其他控件或布局影响了软键盘的显示。鸿蒙Next的TextInput控件提供了丰富的配置选项,开发者可以根据需求进行调整。

需要注意的是,鸿蒙Next的系统行为和API可能与之前的版本有所不同,因此在开发过程中应参考最新的官方文档和API指南,确保代码的兼容性和正确性。如果问题依然存在,可以通过日志分析或调试工具进一步定位问题根源。

在HarmonyOS鸿蒙Next中,短信校验码控件的软键盘问题可能涉及输入法的兼容性或焦点管理。建议检查以下几点:

  1. 焦点管理:确保输入框正确获取焦点,触发软键盘弹出。
  2. 输入法兼容性:测试不同输入法,确保与系统默认输入法兼容。
  3. 布局优化:调整布局,避免软键盘遮挡输入框,可通过监听键盘事件动态调整UI。
  4. 系统版本:确认系统版本,更新至最新以修复已知问题。

若问题依旧,建议提交日志供开发团队分析。

回到顶部