public class CqrKeyboardListen implements ViewTreeObserver.OnGlobalLayoutListener {
private View contentView;
private int originVisibleH;
private OnKeyboardListener onKeyboardListener;
private CqrKeyboardListen(Activity activity, OnKeyboardListener listener) {
if (activity == null) {
return;
}
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
onKeyboardListener = listener;
contentView = activity.findViewById(android.R.id.content);
if (contentView != null) {
contentView.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
}
public static CqrKeyboardListen listen(Activity activity, OnKeyboardListener listener) {
return new CqrKeyboardListen(activity, listener);
}
@Override
public void onGlobalLayout() {
if (onKeyboardListener == null) {
return;
}
//布局变化,获取当前根视图在屏幕上显示的高度
Rect rect = new Rect();
contentView.getWindowVisibleDisplayFrame(rect);
int currentVisibleH = rect.height();
if (originVisibleH == 0) {
originVisibleH = currentVisibleH;
}
int diffHeight = originVisibleH - currentVisibleH;
//CqrLogPrinter.printLog("originVisibleH=" + originVisibleH + ",currentVisibleH="
// + currentVisibleH + ",diffHeight=" + diffHeight);
if (diffHeight > 200) {
//根视图显示高度变小超过200,可以看作软键盘显示了
onKeyboardListener.onKeyboardChange(true, diffHeight);
originVisibleH = currentVisibleH;
return;
}
if (diffHeight < -200) {
//根视图显示高度变大超过200,可以看作软键盘隐藏了
onKeyboardListener.onKeyboardChange(false, diffHeight);
originVisibleH = currentVisibleH;
}
}
/**
* 在{@link Activity#onDestroy()}中调用,防止内存泄漏
*/
public void destroy() {
if (contentView != null) {
CqrCompatUtils.removeOnGlobalLayoutListener(contentView, this);
}
}
public interface OnKeyboardListener {
void onKeyboardChange(boolean isShow, int keyboardHeight);
}
}
使用:
keyboardListen = CqrKeyboardListen.listen(activity, new CqrKeyboardListen.OnKeyboardListener() {
@Override
public void onKeyboardChange(boolean isShow, int keyboardHeight) {
// DO SOMETHING
}
});
作者的是有点问题,更改为这个就可以了:
使用: