输入框拉起键盘时,如何将底部布局弹起到键盘顶部

软件盘弹出的时候默认是顶起输入框,对于输入框以下的显示组件将被遮挡。

HarmonyOS
2024-03-17 15:13:17
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
milchcow

获取窗口内容规避的区域,规避区域的类型是软键盘区域TYPE_KEYBOARD,当软键盘弹出,获取规避区域的高度,通过margin-bottom来设置,顶起组件。参考代码如下:

import { window } from '@kit.ArkUI'; 
 
@Entry 
@Component 
struct ScrollExample { 
  scroller: Scroller = new Scroller(); 
  private arr: number[] = [0, 1, 2, 3, 4, 5]; 
  @State scrollHeight: number = 0; 
  @State isRebuild: boolean = false; 
  @State keyHeight: number = 0; 
  @State text: string = ''; 
 
  aboutToAppear() { 
    window.getLastWindow(getContext(this)).then(currentWindow => { 
      let property = currentWindow.getWindowProperties(); 
      // 初始化窗口高度 
      let avoidArea = currentWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD); 
      this.scrollHeight = px2vp(property.windowRect.height - avoidArea.bottomRect.height); 
 
      // 监听软键盘的隐藏和显示 
      currentWindow.on('avoidAreaChange', async data => { 
        if (data.type !== window.AvoidAreaType.TYPE_KEYBOARD) { 
          this.keyHeight = avoidArea.bottomRect.height; 
          return; 
        } 
        this.scrollHeight = px2vp(property.windowRect.height - data.area.bottomRect.height); 
      }) 
    }) 
  } 
 
  build() { 
    Stack({ alignContent: Alignment.TopStart }) { 
      Column() { 
        Scroll(this.scroller) { 
          Column() { 
            TextInput({ text: this.text, placeholder: 'input your word...' }) 
              .placeholderFont({ size: 14, weight: 400 }) 
              .width(320) 
              .height(40) 
              .margin(200) 
              .fontSize(14) 
              .fontColor(Color.Black) 
              .backgroundColor(Color.White) 
            ForEach(this.arr, (item: number) => { 
              Text(item.toString()) 
                .width('90%') 
                .height(150) 
                .backgroundColor(0xFFFFFF) 
                .borderRadius(15) 
                .fontSize(16) 
                .textAlign(TextAlign.Center) 
                .margin({ top: 10 }) 
            }) 
          }.width('100%') 
        } 
        .width('100%').height(this.scrollHeight).layoutWeight(1) 
 
        Text('这是一个测试文本') 
          .width('100%') 
          .height(50) 
          .backgroundColor(Color.Red) 
          .margin({ bottom: this.scrollHeight }) 
      }.width('100%').height('100%').justifyContent(FlexAlign.Start) 
 
    }.width('100%').height('100%').backgroundColor(0xDCDCDC) 
  } 
}

参考链接

内容规避区

分享
微博
QQ
微信
回复
2024-03-18 20:52:03
相关问题
H5页面输入框自动获焦弹起键盘
595浏览 • 1回复 待解决
键盘拉起列表无法上下滑动
1007浏览 • 1回复 待解决
js如何清空一个input 输入框的内容
6375浏览 • 1回复 待解决
怎么监听键盘弹起和关闭事件?
1320浏览 • 1回复 待解决
JS UI 怎么判断键盘 是否拉起
5331浏览 • 1回复 待解决
如何将容器定位到屏幕的最底部
998浏览 • 1回复 待解决
如何主动拉起键盘,你知道吗?
1113浏览 • 1回复 待解决