首页 > Android 如果监听 输入法 弹出和关闭 事件

Android 如果监听 输入法 弹出和关闭 事件

以及获取输入法高度。

简单的说就是现在我需要将一个布局放在输入法面板的上面


在网上找了很久,也没找到好的办法,事实上我想实现的效果类似微信朋友圈的评论输入框。

在输入法弹出的时候,后面的内容不会缩放;而评论输入框刚好显示在输入法面板上(above)。

这里不仅需要监听到输入法的弹出和关闭,还要获取到输入法的高度。

要让背景元素不resize。那么android:windowSoftInputMode="adjustNothing"。可是这么设置后又不能监听到输入法的弹出和关闭。(找到的所有方法都是基于adjustResize的)

于是我把android:windowSoftInputMode="adjustResize",但是重载Activity根View(就是setContentView设置的那个)的onMeasure方法。

如果发现输入法没有弹出了,那么onMeasure就直接用传进来的参数调用super.onMeasure()。
如果发现输入法弹出了,那么更改参数,保证View没有缩小。代码如下。

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        Rect r = new Rect();
        getWindowVisibleDisplayFrame(r);

        int totalHeight = getRootView().getHeight();
        int nowHeight = r.bottom - r.top;
        if (totalHeight - nowHeight > totalHeight / 4) {
            super.onMeasure(widthSpec, MeasureSpec.makeMeasureSpec(totalHeight, MeasureSpec.EXACTLY));
            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) panel.getLayoutParams();
            params.bottomMargin = totalHeight - nowHeight;
        } else {
            super.onMeasure(widthSpec, heightSpec);
            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) panel.getLayoutParams();
            params.bottomMargin = 0;
        }
    }

这个功能的实现其实不用这么麻烦。
先设置布局

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent >
    <LinearLayout
        android:id="@+id/commentLayout"
        android:width="match_parent"
        android:height="wrap_content"
        android:layout_alignParentBottom="true">
        <!-- 你的评论布局 -->
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/commentLayout">  
        <!-- 你的列表布局-->
    </LinearLayout>
</RelativeLayout>

然后设置AndroidManifest.xml

android:windowSoftInputMode="adjustResize"

就能实现你想要的效果


上面的是resize,下面的是pan

【热门文章】
【热门文章】