我还没有找到任何方法来解决这个问题。
我的应用中有一个webview。我希望能够检测键盘何时处于活动状态以及何时处于非活动状态。当他们在webview中幸福时,似乎无法检测到这些变化。
我想对这些不同的状态执行操作。在iOS上,它非常简单,观察者在键盘处于活动状态时进行监听。参考UIKeyboardWillShow / Hide。
android中是否有任何功能与android中的观察者一样?
希望问题解释得很好。
答案 0 :(得分:0)
所以我花了一个星期左右的时间来解决这个问题,并找到了很多材料这是我的解决方案,我真的希望它对你有用。
所以在我的例子中,我有一个 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);
//mWebView.postUrl("https://www.google.com/");
final View activityRootView = view;
layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
activityRootView.getWindowVisibleDisplayFrame(r);
// This variable was created only for Debug purposes and
// to see the height change when clicking on a field inside mWebView
int screenHeight = activityRootView.getRootView().getHeight();
Log.d("onGlobalLayout", "rect: " + r.toString());
Log.d("onGlobalLayout", "screenHeight: " + screenHeight);
//The difference on the heights from bottom to top and on the root height
int heightDiff = screenHeight - (r.bottom - r.top);
Log.d("onGlobalLayout", "heightDiff: " + heightDiff);
//I suggest to put 250 on resources and retrieve from there using getResources().getInteger() to have better order
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;// this is used to avoid multiple assignments
private ViewTreeObserver.OnGlobalLayoutListener layoutListener = null;
终于
@Override
public void onPause() {
super.onPause();
final View activityRootView = getActivity().findViewById(R.id.page_content);
activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(layoutListener);
}
这应该可以解决问题:) 那你怎么看?