版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010356768/article/details/89532846
private void setListenerToRootView() {
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) {
Toast.makeText(EdittextActivity.this, "键盘弹出", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(EdittextActivity.this, "键盘收起", Toast.LENGTH_SHORT).show();
}
//如果只想检测一次,需要注销
//rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
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;
}