Android 监听键盘弹出/隐藏
在部分安卓机型遇到 SoftInputMode 设置 adjustPan / adjustResize 无效的情况。于是对键盘做了单独的监听,方便统一处理
private int oldDiff = 0; @Override protected void onCreate(...) { listenKeyboardVisible(); } private void listenKeyboardVisible() { final View activityRoot = getWindow().getDecorView(); if (activityRoot ==null) { return; } mainContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { private final Rect r =new Rect(); @Override public void onGlobalLayout() { activityRoot.getWindowVisibleDisplayFrame(r); int diff = activityRoot.getRootView().getHeight() -r.height(); //键盘是否弹出 boolean isOpen = (diff > 200); if(diff!=oldDiff){ Log.d("keyboard", "keyboard open: "+isOpen); oldDiff = diff; // do someting... } } }); }