我试图检查键盘是否可见。我编写代码,我的代码在Activity和一些样式中完美运行。这是我的来源
public class KeyboardVisibilityEvent {
private final static int KEYBOARD_VISIBLE_THRESHOLD_DP = 100;
public static void setEventListener(final Activity activity,
final KeyboardVisibilityEventListener listener) {
if (activity == null) {
throw new NullPointerException("Parameter:activity must not be null");
}
if (listener == null) {
throw new NullPointerException("Parameter:listener must not be null");
}
final View activityRoot = getActivityRoot(activity);
final ViewTreeObserver.OnGlobalLayoutListener layoutListener =
new ViewTreeObserver.OnGlobalLayoutListener() {
private final Rect r = new Rect();
private final int visibleThreshold = Math.round(
UIUtil.convertDpToPx(activity, KEYBOARD_VISIBLE_THRESHOLD_DP));
private boolean wasOpened = false;
@Override
public void onGlobalLayout() {
activityRoot.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRoot.getRootView().getHeight() - r.height();
boolean isOpen = heightDiff > visibleThreshold;
if (isOpen == wasOpened) {
return;
}
wasOpened = isOpen;
listener.onVisibilityChanged(isOpen);
}
};
activityRoot.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
activity.getApplication()
.registerActivityLifecycleCallbacks(new AutoActivityLifecycleCallback(activity) {
@Override
protected void onTargetActivityDestroyed() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
activityRoot.getViewTreeObserver()
.removeOnGlobalLayoutListener(layoutListener);
} else {
activityRoot.getViewTreeObserver()
.removeGlobalOnLayoutListener(layoutListener);
}
}
});
}
public static boolean isKeyboardVisible(Activity activity) {
Rect r = new Rect();
View activityRoot = getActivityRoot(activity);
int visibleThreshold =
Math.round(UIUtil.convertDpToPx(activity, KEYBOARD_VISIBLE_THRESHOLD_DP));
activityRoot.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRoot.getRootView().getHeight() - r.height();
return heightDiff > visibleThreshold;
}
private static View getActivityRoot(Activity activity) {
return ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
}
}
KeyboardVisibilityEvent.setEventListener(this, new KeyboardVisibilityEventListener() {
@Override
public void onVisibilityChanged(boolean isOpen) {
}
});
正如我所说,这段代码完美无缺,但现在我想在Fragment中使用这段代码。 My Fragment的SoftInputMode是SOFT_INPUT_ADJUST_NOTHING。
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
并且在Manifest源中
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/NoTitleBar"
android:configChanges="locale"
android:windowSoftInputMode="adjustNothing">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
当InputMode为adjustNothing时,是否可以检查键盘的可见性? 谢谢大家!