我曾经为此苦苦挣扎了一周左右,找到了很多资料。这是我的解决方案,真心希望它能对你有所帮助。
在我的情况下,我有一个Activity,并调用包含Webview的片段,所以比我想象的要棘手得多。
基本上问题在于该片段缺少了这一行:
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
所以它没有识别到Webview内高度的变化。
无论如何,让我们来看看代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
final View activityRootView = view;
layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
activityRootView.getWindowVisibleDisplayFrame(r);
int screenHeight = activityRootView.getRootView().getHeight();
Log.d("onGlobalLayout", "rect: " + r.toString());
Log.d("onGlobalLayout", "screenHeight: " + screenHeight);
int heightDiff = screenHeight - (r.bottom - r.top);
Log.d("onGlobalLayout", "heightDiff: " + heightDiff);
float dpx = dpToPx(getActivity(), 250);
if (previousHeightDiff != heightDiff) {
if (heightDiff > dpx) {
isSoftKeyboardPresent = true;
} else {
isSoftKeyboardPresent = false;
}
previousHeightDiff = heightDiff;
}
}
};
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
return view;
}
private static float dpToPx(Context context, float valueInDp) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
}
请记得在AndroidManifest.xml文件中的Activity设置中添加以下内容:android:windowSoftInputMode="adjustResize|stateHidden"
片段内的变量有:
public boolean isSoftKeyboardPresent = false
private int previousHeightDiff = -1
private ViewTreeObserver.OnGlobalLayoutListener layoutListener = null
最后
@Override
public void onPause() {
super.onPause();
final View activityRootView = getActivity().findViewById(R.id.page_content);
activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(layoutListener);
}
这应该就可以解决问题了 :) 你觉得呢?