代码很简单,可以直接复制粘贴。
原理请参照:http://blog.youkuaiyun.com/xiaole0313/article/details/51537809
private void setListenerToRootView() {
final View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LogUtils.d(TAG, "[onGlobalLayout] .. in ..");
boolean mKeyboardUp = isKeyboardShown(rootView);
if (mKeyboardUp) {
LogUtils.d(TAG, "键盘弹出..");
} else {
LogUtils.d(TAG, "键盘收起..");
}
}
});
}
private boolean isKeyboardShown(View rootView) {
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}