Android-监听虚拟键盘状态

Android系统未直接提供虚拟键盘状态API,但可通过监听页面根布局变化实现。需在清单文件中将活动的android:windowSoftInputMode设为adjustResize,以确保键盘显示时布局发生变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android系统本身没有提供监听虚拟键盘的隐藏或显示API,
要实现该功能,我们需要间接来解决,当虚拟键盘显示/隐藏是页面当布局会发生改变,我们可以监听页面的RootView的布局变化来解决该问题:

关键代码如下:

public class TestActivity extends Activity {


    private ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        //create a listener to listen root view layout's status
        mGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                final Rect r = new Rect();
                //r will be populated with the coordinates of your view that area still visible.
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);

                int originDecordViewHeight = getWindow().getDecorView().getHeight();
                int visibleDecordViewHeight = r.bottom - r.top;//not include status bar
                final int heightDiff = originDecordViewHeight - visibleDecordViewHeight;

                if (heightDiff > 200) {
                    //当heightDiff大于某个阀值(此处测试方便设为200)可以认为是键盘出现
                    onKeybaordShow();
                } else {
                    //键盘消失
                    onKeybaordHide();
                }
            }


        };

        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //反注册,避免内存泄漏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(mGlobalLayoutListener);
        }
        mGlobalLayoutListener = null;
    }
}

注意:清单文件中TestActivity 的android:windowSoftInputMode需设置adjustResize,否则键盘显示页面布局不会变化,上述的方法也就失效了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值