6

Is it possible to detect whether a keyboard is visible on the screen or not?

Thanks

aryaxt
  • 76,198
  • 92
  • 293
  • 442

3 Answers3

3

I think this thread should answer your question. To summarize, you can give your activity's root view an id, such as "@+id/activityRoot", and then hook a GlobalLayoutListener into the ViewTreeObserver for that view. In the listener is where you check the visibility of the keyboard, like so:

final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
    if (getResources().getConfiguration().keyboardHidden == Configuration.KEYBOARDHIDDEN_NO) { // Check if keyboard is not hidden
     // ... do something here
    }
  }
});

This is a combination of @Reuben_Scratton and @Yogesh's answers in the above thread.

UPDATE: Note that the documentation for keyboardHidden says it will ALWAYS return Configuration.KEYBOARDHIDDEN_YES if there is a hard keyboard available on the device(i.e. like a Motorola Droid 1 & 2)

Community
  • 1
  • 1
cbradley
  • 131
  • 2
  • 5
  • 4
    It doesn't work. It always returns Configuration.KEYBOARDHIDDEN_NO to me (no hard keyboard on my device). – Yi H. Jun 17 '13 at 11:03
1

try this or this workaround since its not possible within "simple" sdk method invocation

Community
  • 1
  • 1
Rafael T
  • 15,401
  • 15
  • 83
  • 144
-3

You might try something along the lines of this:

InputMethodManager imm = 
    (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
boolean showingKeyboard = imm.isActive();

Hope this helps!

EDIT:

The other option is simply to force the keyboard open or closed, depending on what you want the user to see :) This would lead to more predictable use behavior and likely improve the user experience.

Codeman
  • 12,157
  • 10
  • 53
  • 91
  • 1
    It returns true all the time, even when my keyboard is not visible on the screen – aryaxt Dec 08 '11 at 19:38
  • this will not work if someone is using long-press-menu to trigger the keyboard. It tells you only if a view is active for recieving soft-keyboard events. – Rafael T Dec 08 '11 at 19:39
  • @Pheonixblade9: This does not work, read the docu on `isActive()` more carefully! It's not about visibility but about the 'active' state. – Bondax Nov 06 '12 at 12:31