方案一:监听布局高度变化,使用屏幕高度减去可用高度,剩余高度即键盘高度
private ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
};
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
int heightDifference;
if (usableHeightNow != mUsableHeightPrevious) {
int usableHeightSansKeyboard = mContentView.getRootView().getHeight();
heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > 200) {
// keyboard probably just became visible
mContentView.setPadding(0, 0, 0, heightDifference);
} else {
// keyboard probably just became hidden
mContentView.setPadding(0, 0, 0, 0);
}
mUsableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
final Rect rect = new Rect();
mContentView.getWindowVisibleDisplayFrame(rect);
return rect.bottom - rect.top;
}
方案二:通过android api30以上提供的新api获取
@RequiresApi(api = Build.VERSION_CODES.R)
private void windowInsets() {
mContentView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
int bottom = insets.getInsets(WindowInsets.Type.ime()).bottom;
mContentView.setPadding(0, 0, 0, bottom);
if (SDKLog.isDebugLoggable())
SDKLog.d(TAG, "ime top:" + insets.getInsets(WindowInsets.Type.ime()).top +
" bottom:" + insets.getInsets(WindowInsets.Type.ime()).bottom);
return insets;
}
});
}