配置键盘避让时页面的避让模式有三种,分别是上抬模式、压缩模式、不避让 接下来通过一个简单案例介绍这三种模式的使用和区别。
例如以下布局,一个顶部的Row按钮区,底部一个固定高度的按钮区,中间内容区域充满剩余部分,三种避让模式的演示如下:

针对以上三种模式存在的不足:
1.上抬模式,整体布局上移,软键盘挡住了底部的按钮区
2.压缩模式,当前布局变形
3.不避让,软键盘弹出会挡住下面大部分区域
如果使用上抬模式 ,我们想固定顶部的按钮区不被顶出去,我们可以给顶部按钮区设置expandSafeArea([SafeAreaType.KEYBOARD]) ,看效果:
发现顶部按钮没有移动,但是内容区域上抬挡住了顶部的按钮区,这时,我们再给顶部区域设置一个zIndex(1)显示层级修改一下,就可以展示到内容区上面了。 这种模式设置,适合顶部区域固定,底部没有展示内容或者可以被遮挡的情况。 如果使用压缩模式 ,如果不考虑内容被压缩,可以满足顶部和底部都能展示出来,但是内容变形怎么处理呢? 因为压缩模式是避让了软键盘的区域,因此布局的高度被压缩了,如果高度设置的是百分比布局,整体高度压缩,自己的高度也会相应的压缩 ,所以,如果使用压缩模式,可以使用实际高度 设置组件的高度。 看一下效果:
因此,采用压缩模式,顶部按钮区、底部按钮区、输入框使用实际高度,中间填充区域使用Scroll布局填充被压缩,即可满足。
源码:
kotlin
import { KeyboardAvoidMode } from '@kit.ArkUI';
@Entry
@ComponentV2
struct KeyboardTest{
@Local safeArea:Array<SafeAreaType> = []
@Local zindex:number = 0;
@Local topHeight:Length = 80;
@Local inputHeight:Length = 80;
build() {
Column({ space:10 }) {
Row() {
Button('上抬避让').onClick(()=>{
this.getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.OFFSET);
})
Button('压缩避让').onClick(()=>{
this.getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
})
Button('不避让').onClick(()=>{
this.getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.NONE);
})
}
.alignItems(VerticalAlign.Bottom)
.backgroundColor(Color.White)
.height(this.topHeight)
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
.padding({ left: 10, right: 10, bottom: 20 })
.expandSafeArea(this.safeArea)
.zIndex(this.zindex)
Row({ space:10 }){
Button('固定顶部').onClick(()=>{
this.safeArea = [SafeAreaType.KEYBOARD]
this.zindex=1
})
Button('固定高度').onClick(()=>{
this.topHeight = 80
this.inputHeight = 80
})
Button('百分比高度').onClick(()=>{
this.topHeight = '10%'
this.inputHeight = '10%'
})
}
.padding({ left: 10, right: 10})
Scroll(){
Column({ space:20 }){
TextArea({ placeholder: '名字' })
.height(this.inputHeight)
.width('100%')
.padding(10)
.enterKeyType(EnterKeyType.Next)
.onSubmit((enterKey: EnterKeyType, event: SubmitEvent)=>{
if (enterKey.valueOf()==EnterKeyType.Next) {
focusControl.requestFocus('123')
// 调用keepEditableState方法,输入框保持编辑态
event.keepEditableState();
}
})
TextArea({ placeholder: '性别' })
.height(this.inputHeight)
.width('100%')
.padding(10)
.id('123')
TextArea({ placeholder: '专业' })
.height(this.inputHeight)
.width('100%')
.padding(10)
TextArea({ placeholder: 'ID' })
.height(this.inputHeight)
.width('100%')
.padding(10)
TextArea({ placeholder: '住址' })
.height(this.inputHeight)
.width('100%')
.padding(10)
TextArea({ placeholder: '籍贯' })
.height(this.inputHeight)
.width('100%')
.padding(10)
}
}
.layoutWeight(1)
Row() {
Text('1').width(30).height(30)
Text('2').width(30).height(30)
Text('3').width(30).height(30)
Text('4').width(30).height(30)
Text('5').width(30).height(30)
}
.width('100%')
.height(40)
.backgroundColor('#F1F1F1')
.justifyContent(FlexAlign.SpaceEvenly)
.margin({ bottom: 20 })
}.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Start)
}
}