How to capture the "virtual keyboard show/hide" event in Android?


I would like to alter the layout based on whether the virtual keyboard is shown or not. I've searched the API and various blogs but can't seem to find anything useful.

Is it possible?


7/18/2016 12:44:24 PM

Accepted Answer


This solution will not work for soft keyboards and onConfigurationChanged will not be called for soft (virtual) keyboards.

You've got to handle configuration changes yourself.


// from the link above
public void onConfigurationChanged(Configuration newConfig) {

    // Checks whether a hardware keyboard is available
    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();

Then just change the visibility of some views, update a field, and change your layout file.

8/15/2019 10:19:13 AM

This may not be the most effective solution. But this worked for me every time... I call this function where ever i need to listen to the softKeyboard.

boolean isOpened = false;

public void setListenerToRootView() {
    final View activityRootView = getWindow().getDecorView().findViewById(;
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        public void onGlobalLayout() {

            int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
            if (heightDiff > 100) { // 99% of the time the height diff will be due to a keyboard.
                Toast.makeText(getApplicationContext(), "Gotcha!!! softKeyboardup", 0).show();

                if (isOpened == false) {
                    //Do two things, make the view top visible and the editText smaller
                isOpened = true;
            } else if (isOpened == true) {
                Toast.makeText(getApplicationContext(), "softkeyborad Down!!!", 0).show();
                isOpened = false;

Note: This approach will cause issues if the user uses a floating keyboard.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow