HarmonyOS UI组件如何知道弹出了软键盘

HarmonyOS
2025-01-09 16:23:25
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

可通过以下两个方案实现:

1、可在EntryAbility下设置监听键盘状态的变化,设置键盘弹起的高度,联合padding中设置{bottom:px2vp(this.keyboardHeight)}可以将元素底部将保持与视口底部的相对距离和expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM])方法将将指定的安全区域类型(此处为键盘)的指定边缘(此处为底部)扩展实现软键盘拉起时可以将页面数据顶上去,避免软键盘遮住底部页面信息。

EntryAbility代码:

windowStage.getMainWindow((err, data) => {
  if (err.code) {
    console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
    return;
  }
  let windowClass = data;
  //1. 设置监听键盘变化,用来设置inputview 避让输入法
  try {
    windowClass.on('keyboardHeightChange', (data) => {
      console.info('keyboardHeightChange. Data: ' + JSON.stringify(data));
      AppStorage.setOrCreate('keyboardHeight', data);
      console.info(AppStorage.get('keyboardHeight'))
    });
  } catch (exception) {
    console.error('Failed to enable the listener for keyboard height changes. Cause: ' + JSON.stringify(exception));
  }
})

主页面代码:

import router from '@ohos.router';
import deviceInfo from '@ohos.deviceInfo';

@Entry
@Component
struct Index2 {
  @StorageLink('keyboardHeight') keyboardHeight: number = 0;
  controller: TextInputController = new TextInputController()
  @State username: string = ''
  @State password: string = ''

  build() {
    Column({ space: 20 }) {
      Text('用户登录').textAlign(TextAlign.Center).fontSize(50)
      Row({ space: 10 }) {
        Text('用户名:').textAlign(TextAlign.Start)
        TextInput({
          placeholder: '', text: this.username,
          controller: this.controller
        }).width('80%').onChange((data) => {
          this.username = data
        })
      }.width('100%')

      Row({ space: 20 }) {
        Text('密 码:').textAlign(TextAlign.Start)
        TextInput({
          placeholder: '', text: this.password,
          controller: this.controller
        }).width('80%').type(InputType.Password).onChange((data) => {
          this.password = data
        })
      }.width('100%')

      Row({ space: 50 }) {
        Button('登录').type(ButtonType.Capsule).width(100).onClick(() => {
          console.info(`${this.password} ${this.username}`);
          if (this.username === '123456789' && this.password === '112233') {
            router.pushUrl({ url: 'pages/Index' })
          } else if (this.username === '' ||
            this.password === '' || this.username === undefined || this.password === undefined) {
            AlertDialog.show({ message: '用户名或密码不能为空' });
          } else {
            AlertDialog.show({ message: '用户名或密码错误!' });
          }
        })
        Button('重置').type(ButtonType.Capsule).width(100).onClick(() => {
          this.username = ""
          this.password = ""
        })
      }
    }
    .padding(30)
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.SpaceEvenly)
    .padding({ bottom: px2vp(this.keyboardHeight) }) //配合expandSafeArea, 实现避让键盘
    .expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM])
  }
}

2、直接在主页面中进行监听。

import window from '@ohos.window';

@Entry
@Component
struct Index {
  @State screenHeight: number = 0;

  aboutToAppear() {
    window.getLastWindow(getContext(this)).then(currentWindow => {
      let property = currentWindow.getWindowProperties();
      let avoidArea = currentWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD);
      // 初始化显示区域高度
      this.screenHeight = px2vp(property.windowRect.height - avoidArea.bottomRect.height);
      // 监视软键盘的弹出和收起
      currentWindow.on('avoidAreaChange', async data => {
        if (data.type !== window.AvoidAreaType.TYPE_KEYBOARD) {
          return;
        }
        this.screenHeight = px2vp(property.windowRect.height - data.area.bottomRect.height);
      })
    })
  }

  build() {
    Row() {
      Column() {
        Text('请输入短信验证码')
          .fontSize(30)
          .margin({
            bottom: '50'
          })
        TextInput()
          .width('70%')
          .height('150px')
          .margin({
            bottom: '30'
          })
        Button('确定')
          .width('70%')
          .margin('20px')
      }
      .width('100%')
    }
    .width('100%').height(this.screenHeight)
  }
}
分享
微博
QQ
微信
回复
2025-01-09 18:10:15
相关问题
HarmonyOS 如何监听软键盘弹出
506浏览 • 1回复 待解决
如何判断软键盘是否弹出
2365浏览 • 1回复 待解决
HarmonyOS 软键盘弹出方式
360浏览 • 1回复 待解决
HarmonyOS 如何代码控制软键盘弹出
786浏览 • 1回复 待解决
HarmonyOS 软键盘弹出隐藏监听
502浏览 • 1回复 待解决
关于软键盘弹出遮挡问题
1497浏览 • 1回复 待解决
HarmonyOS 软键盘弹出控制与检测
289浏览 • 1回复 待解决
HarmonyOS 软键盘弹出后又突然消失
373浏览 • 1回复 待解决
HarmonyOS 弹出软键盘时,web页面白屏
439浏览 • 1回复 待解决
软键盘弹出时,页面的自适应
1858浏览 • 1回复 待解决
如何控制软键盘弹出对页面的遮挡?
2939浏览 • 1回复 待解决
window模拟器无法弹出软键盘
435浏览 • 1回复 待解决
如何主动拉起软键盘,你知道吗?
3044浏览 • 1回复 待解决
HarmonyOS是否有弹出隐藏软键盘的api
330浏览 • 1回复 待解决
鸿蒙软键盘弹出后,页面底部的按钮
4483浏览 • 0回复 待解决