Skip to content

Instantly share code, notes, and snippets.

@yqritc
Last active October 29, 2021 01:41
Show Gist options
  • Save yqritc/efa7bf4a9b060a74d27a to your computer and use it in GitHub Desktop.
Save yqritc/efa7bf4a9b060a74d27a to your computer and use it in GitHub Desktop.
Manage Android Software Keyboard Visibility

Caution

The ways to manage Android software keyboard visibility have already discussed so much on web.
But some of old solutions on web does not work since the view hierarchy of Activity changes over time.
Therefore, the following solution may not work in the future.

KeyboardHelper

public class KeyboardHelper {

    public interface KeyboardListener {

        void onShowKeyboard();

        void onHideKeyboard();
    }

    public static ViewTreeObserver.OnGlobalLayoutListener setKeyboardListener(
            @NonNull View rootChildView, @NonNull KeyboardListener listener) {
        return () -> {
            int bottomPadding = rootChildView.getPaddingBottom();
            if (bottomPadding > 0) {
                listener.onShowKeyboard();
            } else {
                listener.onHideKeyboard();
            }
        };
    }
}

Implementation

Add the following code in onCreate of your activity.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);

        ViewGroup rootView = (ViewGroup) mYourLayoutRootView.getRootView();
        View rootChildView = rootView.getChildAt(0);
        mKeyboardLayoutListener = KeyboardHelper.setKeyboardListener(rootChildView, this);
        mYourLayoutRootView.getViewTreeObserver().addOnGlobalLayoutListener(mKeyboardLayoutListener);
    }

Also, implement KeyboardListener.

    @Override
    public void onShowKeyboard() {
        // some code
    }

    @Override
    public void onHideKeyboard() {
        // some code
    }

And do not forget to remove ViewTreeObserver.OnGlobalLayoutListener.

    @Override
    protected void onDestroy() {
        mYourLayoutRootView.getViewTreeObserver().removeOnGlobalLayoutListener(mKeyboardLayoutListener);
        super.onDestroy();
    }

Please note that onShowKeyboard and onHideKeyboard methods are called multiple times.
If you want to avoid its behaviour, define flag to control it.

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