-
-
Save gitzxon/03c946242e55d7fcf77dfafae55c5e14 to your computer and use it in GitHub Desktop.
find the soft keyboard height, and scroll the target view when it is hidden by the soft keyboard.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class KeyboardUtil { | |
public static void hide(View v) { | |
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); | |
if (imm != null && imm.isActive()) { | |
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0); | |
} | |
} | |
public interface SoftKeyboardCallback { | |
void onShow(int screenHeight, int viewBottom); | |
void onHide(); | |
} | |
public static ViewTreeObserver.OnGlobalLayoutListener detectSoftKeyboard(View view, SoftKeyboardCallback softKeyboardCallback) { | |
if (view == null) { | |
return null; | |
} | |
ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = () -> { | |
Rect r = new Rect(); | |
view.getWindowVisibleDisplayFrame(r); | |
int screenHeight = view.getRootView().getHeight(); | |
// r.bottom is the position above soft keypad or device button. | |
// if keypad is shown, the r.bottom is smaller than that before. | |
int keypadHeight = screenHeight - r.bottom; | |
// 0.15 ratio is perhaps enough to determine keypad height. | |
if (keypadHeight > screenHeight * 0.15) { | |
// keyboard is opened | |
softKeyboardCallback.onShow(screenHeight, r.bottom); | |
} else { | |
// keyboard is closed | |
softKeyboardCallback.onHide(); | |
} | |
}; | |
view.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener); | |
return onGlobalLayoutListener; | |
} | |
public static ViewTreeObserver.OnGlobalLayoutListener detectSoftKeyboard( | |
@NonNull View view, | |
@NonNull View targetView, | |
int gap | |
) { | |
return detectSoftKeyboard(view, new SoftKeyboardCallback() { | |
@Override | |
public void onShow(int screenHeight, int viewBottom) { | |
int[] location = new int[2]; | |
targetView.getLocationInWindow(location); | |
int expectedBottom = location[1] + targetView.getMeasuredHeight(); | |
int distance = expectedBottom - viewBottom; | |
if (distance > 0) { | |
distance += gap; | |
targetView.setTranslationY(-distance); | |
} | |
} | |
@Override | |
public void onHide() { | |
targetView.setTranslationY(0); | |
} | |
}); | |
} | |
public static void removeSoftKeyboardDetector(View view, ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener) { | |
if (view != null && onGlobalLayoutListener != null) { | |
view.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment