记录下,下次找起来方便
新建工具类
/**
* 防止软键盘遮挡输入框
*/
public class WindowSoftModeAdjustResizeExecutor {
// For more information, see https://code.google.com/p/android/issues/detail?id=5497
// To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
// CREDIT TO Joseph Johnson (http://stackoverflow.com/users/341631/joseph-johnson) for publishing the original Android solution on stackoverflow.com
public static void assistActivity(Activity activity) {
new WindowSoftModeAdjustResizeExecutor(activity);
}
private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
private WindowSoftModeAdjustResizeExecutor(Activity activity) {
FrameLayout content = activity.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(() -> WindowSoftModeAdjustResizeExecutor.this.possiblyResizeChildOfContent());
frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
mChildOfContent.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return (r.bottom - r.top);
}
return r.bottom;
}
}
在设置布局后使用
WindowSoftModeAdjustResizeExecutor.assistActivity(this);