0
点赞
收藏
分享

微信扫一扫

Android使用OnGlobalLayoutListener检测软键盘是否弹出

Android使用OnGlobalLayoutListener检测软键盘是否弹出_android

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;
}


举报

相关推荐

0 条评论