Last active
February 20, 2018 11:59
-
-
Save kevinjam/b8b04b3d43ea5a1ca47d718954aafa73 to your computer and use it in GitHub Desktop.
Keyboard Utils Android , This Hide , addKeyboardVisibilityListener and show 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
import android.app.Activity; | |
import android.content.Context; | |
import android.graphics.Rect; | |
import android.view.View; | |
import android.view.inputmethod.InputMethodManager; | |
public class KeyboardUtils { | |
public static void hideKeyboard(Activity activity) { | |
View view = activity.findViewById(android.R.id.content); | |
if (view != null) { | |
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); | |
imm.hideSoftInputFromWindow(view.getWindowToken(), 0); | |
} | |
} | |
public static void showKeyboard(Activity activity) { | |
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); | |
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); | |
} | |
public static void addKeyboardVisibilityListener(View rootLayout, OnKeyboardVisibiltyListener onKeyboardVisibiltyListener) { | |
rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(() -> { | |
Rect r = new Rect(); | |
rootLayout.getWindowVisibleDisplayFrame(r); | |
int screenHeight = rootLayout.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; | |
boolean isVisible = keypadHeight > screenHeight * 0.15; // 0.15 ratio is perhaps enough to determine keypad height. | |
onKeyboardVisibiltyListener.onVisibilityChange(isVisible); | |
}); | |
} | |
public interface OnKeyboardVisibiltyListener { | |
void onVisibilityChange(boolean isVisible); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment