Q: How to check visibility of software keyboard in Android?

D: I need to do a very simple thing - find out if the software keyboard is shown. Is this possible in Android?

Test Case #18


File ID: #4737265-0-cc


final View activityRootView = findViewById(R.id.root_view);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
        Log.d(TAG,"TestKeyboardSandboxActivity.onCreate(...).new OnGlobalLayoutListener() {...}.onGlobalLayout() measured height::" +activityRootView.getMeasuredHeight());
        Log.d(TAG,"TestKeyboardSandboxActivity.onCreate(...).new OnGlobalLayoutListener() {...}.onGlobalLayout() Height::" +activityRootView.getHeight());
        if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
            relative.setVisibility(View.GONE);
        } else {
            relative.setVisibility(View.VISIBLE);
        }
    }
});

  1. Hi, Your answer to this post helped me greatly but however, since listener gets called everytime(I do not know why.....) I can not do anything with the layout. For example, I inserted a Toast when Keyboard is showing then the Toast keeps on popping up which means listener is getting called all the time.... Is there anyway to stop this? Is this because I implemented listener on the activity not like the way you created it?
  2. Seems to be doing the trick. Also, if you do not know the root view's ID, here's how you can get the view: `((ViewGroup) findViewById(android.R.id.content)).getChildAt(0)`
  3. Beware that `heightDiff` will always include the height of the action bar. In the new answer that has been ignored by testing if that height is greater than some constant, but 100 pixels is not sufficient for xxhdpi devices such as the Nexus 4. Consider converting that value to DPs if you really want to use this hacky work-around.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: