Skip to content

Instantly share code, notes, and snippets.

@parachvte
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save parachvte/67474c03310d9192a4a5 to your computer and use it in GitHub Desktop.

Select an option

Save parachvte/67474c03310d9192a4a5 to your computer and use it in GitHub Desktop.
Android - Keyboard

1. When activity starts, remove auto focus/keyboard popup, in AndroidManifest.xml

<activty android:windowSoftInputMode="stateHidden">
</activity>

2. When keyboard popup, make the window auto resize

<activty android:windowSoftInputMode="adjustResize">
</activity>

3 Hide keyboard programmatically

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

3.1 When EditText is not focused, hide keyboard

EditText mEditText = (EditText) mView.findViewById(R.id.some_edit_text);
mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            // When loss focus, manually hide the soft keyboard
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
});

4 Show keyboard programmatically

mEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT);

or

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

5 Detect appearance & disappearance of keyboard

  • When keyboard appear (or switches), heightDiff will change to 0, then change to height of Keyboard (300~500px)
  • When keyboard disappear, heightDiff will change to 0, then change to height of vitual buttons (50px for Nexus 7, 75px for Nexus 5)
getView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = mRootView.getRootView().getHeight() - mRootView.getHeight();
        if (heightDiff > 100) {
            onKeyboardDidAppear();
        } else if (heightDiff > 0) {
            onKeyboardDidDisappear();
        }
    }
});

6. If you must use fullscreen activity, give AndroidBug5497Workaround.java a try :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment