19

I am trying to listen for events that occurs when the keyboard is shown or hidden. Is this possible in Android? I am not trying to figure out if the keyboard is shown or hidden when I start my activity, I would like to listen for events.

AlexanderNajafi
  • 1,631
  • 2
  • 25
  • 39

1 Answers1

16

Try below code:-

// from the link above
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(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();
    }
}

or

boolean isOpened = false;

 public void setListnerToRootView(){
    final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content); 
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        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;
            }
         }
    });
}

or

for below code you have to extend LinearLayout.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
    final int actualHeight = getHeight();

    if (actualHeight > proposedheight){
        // Keyboard is shown
    } else {
        // Keyboard is hidden
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

see below link:-

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

Community
  • 1
  • 1
duggu
  • 37,851
  • 12
  • 116
  • 113
  • 1
    The first one only works for hard keyboards. The second is not possible to do, how can i override onMeasure(int, int)? – AlexanderNajafi Jun 24 '14 at 14:06
  • @alexandernajafi first of all sorry for late reply now there several method to detect keyborad so please use above method or see the link. – duggu Jun 25 '14 at 04:22