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;
}
Android使用OnGlobalLayoutListener检测软键盘是否弹出
最新推荐文章于 2025-05-06 23:10:53 发布