Android: 记一个关于获取输入法弹起高度的新方式

很久没写博客,最近项目遇到需要获取输入法高度将EditText上移的效果,实现方式本来有几种

1.设置softInputMode WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
但是这样布局中如果有RecyclerView,或者ScrollView的时候,整个布局会向上滚动,但是我不想让他滚动,
执行编辑框上移

2.网上有一个SoftSoftInputKeyBoardUtil类,原理是通过获取可见高度来计算键盘高度,但是测试发现有些手机获取到的高度是不正确的,
有的高一些,有的低一些,(普遍是状态栏和导航栏的高度影响),特别是一些手机有导航栏一键隐藏功能,可以随时显示或隐藏导航栏,
设置隐藏时候,如果弹出输入法,又会自动加上导航栏,导致高度计算错误

下面介绍一种新的实现方式,从fitSystemWindow的灵感发现。(softInputMode需要是adjustResize
设置fitSystemWindow后,会发现我们即使不用上面的监听方法,编辑框也能自己被输入法推上去,但是缺点是View会被添加一段白色的长条,这是由于适应适应系统窗口,系统会为我们给布局view加上pading,留出系统窗口占据的大小,但是有一些浸入式的实现方式可能会被破坏,需要我们手动修改状态栏颜色,从而有可能影响到其他页面的状态栏颜色(如果未及时重置颜色)

1.相关类

从源码中发现这样一个方法,在View和ViewCompat类中

View.java

/**
     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
     * window insets to this view. The listener's
     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
     * method will be called instead of the view's
     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
     *
     * @param listener Listener to set
     *
     * @see #onApplyWindowInsets(WindowInsets)
     */
    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
        getListenerInfo().mOnApplyWindowInsetsListener = listener;
    }

ViewCompat.java

/**
     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
     * window insets to this view. This will only take effect on devices with API 21 or above.
     */
    public static void setOnApplyWindowInsetsListener(@NonNull View v,
            final OnApplyWindowInsetsListener listener) {
        if (Build.VERSION.SDK_INT >= 21) {
            if (listener == null) {
                v.setOnApplyWindowInsetsListener(null);
                return;
            }

            v.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                @Override
                public WindowInsets onApplyWindowInsets(View view, WindowInsets insets) {
                    WindowInsetsCompat compatInsets = WindowInsetsCompat.wrap(insets);
                    compatInsets = listener.onApplyWindowInsets(view, compatInsets);
                    return (WindowInsets) WindowInsetsCompat.unwrap(compatInsets);
                }
            });
        }
    }

两者没有太大差别,ViewCompat帮我们对View中的一些方法做了版本兼容

api介绍是这个listener会去接管view中对于窗口嵌入物的处理,

2.窗口嵌入物都指什么

嵌入物的数据通过WindowInsets表示

稍微看下WindowInsets

重点看下mSystemWindowInsets

public final class WindowInsets {

/**
     * Returns the left system window inset in pixels.
     *
     * <p>The system window inset represents the area of a full-screen window that is
     * partially or fully obscured by the status bar, navigation bar, IME or other system windows.
     * </p>
     *
     * @return The left system window inset
     * 
	 * 这个表示全屏模式下,部分或者全部被状态栏,导航栏,输入法或其他系统窗口遮挡的那部分区域
	 * 这些代码是我从这个类下两个地方拼接的,方便说明这个变量
     */
	private Rect mSystemWindowInsets;


    private Rect mWindowDecorInsets;
    private Rect mStableInsets;
    private Rect mTempRect;
    private boolean mIsRound;
    private DisplayCutout mDisplayCutout;
}

systemWindowInset就是我们要用的东西

/**
     * Returns the left system window inset in pixels.
     * @return The left system window inset
     */
    public int getSystemWindowInsetLeft() {
        return mSystemWindowInsets.left;
    }

    /**
     * Returns the top system window inset in pixels.
     * @return The top system window inset
     */
    public int getSystemWindowInsetTop() {
        return mSystemWindowInsets.top;
    }

    /**
     * Returns the right system window inset in pixels.
     * @return The right system window inset
     */
    public int getSystemWindowInsetRight() {
        return mSystemWindowInsets.right;
    }

    /**
     * Returns the bottom system window inset in pixels.
     * @return The bottom system window inset
     */
    public int getSystemWindowInsetBottom() {
        return mSystemWindowInsets.bottom;
    }

这几个方法,分别获取左,上,右,下位置的遮挡

在这里插入图片描述
这2个值就是从手机边缘算起,嵌入物遮挡的距离

结论:我们可以给View设置这个Listener,获取WindowInsets,获取 getSystemWindowInsetBottom 得到底部被系统窗口嵌入物遮挡的距离,这样就由系统去计算移动的距离(不管你是导航栏还是输入法还是其他的,或者一起出现,遮挡窗口),然后将需要上移的view移动这个距离,通过设置padding或者marin即可。

ViewCompat.setOnApplyWindowInsetsListener(this) { _, insets ->
            setPadding(0, 0, 0, insets.systemWindowInsetBottom)
            insets
        }

这样就可以实现输入法弹起,编辑框上移,关闭输入法,编辑框复原位置

ViewCompat.setOnApplyWindowInsetsListener() 兼容到api 21 也就是5.0

View.setOnApplyWindowInsetsListener() 要求最低版本 20

更低版本可以通过覆写View onApplyWindowInsets来获取WindowInsets

再次提醒: windowSoftInputMode 设置未adjustResize

如果有错误,欢迎讨论,如果能解决你的问题,那就太高兴了

欢迎留言,让我知道这篇文章是否对大家有帮助

<think>好的,我现在需要解决用户提出的微信小程序中输入法弹出时页面被顶起的问题。用户引用了三个参考资料,我需要仔细分析这些资料,找出解决方案。 首先,用户提到的引用[1]和[2]都描述了问题现象:当底部input输入框获取焦点时,键盘弹起导致页面整体上移,标题栏被顶上去。引用[3]则指出可能是因为页面设置了固定高度和滚动轴,导致输入法弹出时没有正确调整布局。解决方案建议不要设置死高度,让内容自适应,这样输入法弹出时整个页面自然上移。 接下来,我需要整理解决方案的步骤。根据引用内容,可能的方法包括: 1. 检查页面布局是否使用固定高度,改为自适应布局,比如使用flex布局。 2. 确保页面滚动设置正确,避免使用固定高度的滚动容器。 3. 在需要时,使用adjust-position属性控制键盘弹起时的行为。 4. 针对特定平台(如iOS)可能需要调整样式,比如使用padding-bottom来适应软键盘。 然后,我需要考虑如何将这些步骤具体化,可能需要代码示例,比如修改CSS样式或调整input组件的属性。同时,要注意不同平台的兼容性问题,比如iOS和Android可能有不同的表现,需要分别处理。 另外,用户提供的参考资料中提到的解决方案是否有效?比如引用[3]中的建议是否经过验证?可能需要确认在uni-app或原生小程序中的具体实现方式。 可能遇到的问题:如果页面结构复杂,单纯改为自适应布局可能不够,需要进一步调整其他元素的样式,或者使用JavaScript动态计算高度。此外,某些情况下可能需要监听键盘高度变化,动态调整布局,但这是否在小程序中可行? 总结解决方案步骤: 1. 避免固定高度,使用flex布局让内容自适应。 2. 移除可能影响页面滚动的样式,如overflow-y: scroll。 3. 在input组件中添加adjust-position="{{false}}"属性,并手动处理布局调整。 4. 针对iOS可能需要额外的padding-bottom来适应键盘。 需要验证这些步骤是否有效,可能需要代码示例和注意事项,比如测试不同平台的表现,确保标题栏不被顶出视图。</think>### 微信小程序输入法弹出导致页面顶起问题解决方案 #### 问题分析 当微信小程序底部`input`输入框聚焦时,键盘弹起会导致页面整体上移,标题栏被顶出可视区域[^1][^2]。主要原因是: 1. 页面布局使用了固定高度或滚动容器,导致键盘弹起时页面压缩异常[^3]; 2. 未正确处理键盘高度与页面布局的适配关系。 --- ### 解决方案步骤 #### 1. 自适应布局改造 **关键点**:使用弹性布局替代固定高度 ```html <!-- page.wxml --> <view class="container"> <view class="header">标题栏</view> <scroll-view scroll-y class="content"> <!-- 页面主要内容 --> </scroll-view> <view class="input-box"> <input adjust-position="{{false}}"/> </view> </view> ``` ```css /* page.wxss */ .container { height: 100vh; display: flex; flex-direction: column; } .content { flex: 1; overflow-y: auto; } .input-box { padding: 10rpx 20rpx; background: #fff; } ``` #### 2. 禁用自动调整 在`input`组件添加属性: ```html <input adjust-position="{{false}}"/> ``` 该设置会阻止系统自动调整页面位置,改为手动控制布局变化。 #### 3. 动态适配键盘高度(进阶方案) ```javascript // page.js Page({ data: { keyboardHeight: 0 }, onKeyboardHeightChange(res) { this.setData({ keyboardHeight: res.height }) } }) ``` ```css /* 动态调整输入框位置 */ .input-box { padding-bottom: env(safe-area-inset-bottom); transition: transform 0.3s; } .input-box.active { transform: translateY(-{{keyboardHeight}}px); } ``` --- ### 注意事项 1. **iOS特殊处理**: 在`scroll-view`底部添加安全区域: ```css scroll-view { padding-bottom: constant(safe-area-inset-bottom); padding-bottom: env(safe-area-inset-bottom); } ``` 2. **滚动穿透问题**: 当键盘弹起时,可在`scroll-view`外层添加`catch:touchmove`阻止页面滚动。 3. **兼容性测试**: Android和iOS系统对`env(safe-area-inset-bottom)`的支持存在差异,需进行真机测试。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值