/**
* 监听键盘开关
*/
private void setKeyboardListener() {
final View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
boolean mKeyboardUp = isKeyboardShown(rootView);
if (mKeyboardUp) {
// 键盘弹出
} else {
// 键盘收起
}
}
});
}
/**
* 当前键盘是否显示
*
* @param rootView rootView
* @return bool
*/
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;
}
在需要的地方,如onCreate里调用setKeyboardListener即可