Android-监听虚拟键盘状态

来源:互联网 发布:淘宝天猫店有保障吗 编辑:程序博客网 时间:2024/05/10 21:34

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,否则键盘显示页面布局不会变化,上述的方法也就失效了