How can Android judge whether the soft keyboard pops up (display)

Posted by TashaAT on Mon, 06 Jan 2020 21:42:57 +0100

In development, sometimes when you exit the interface, if the keyboard pops up, you need to close the keyboard first, and then exit the Activity, how can you change the operation? Please see the following ways?

if (inputMethodManager.isActive(editText)) {  
    Toast.makeText(MainActivity.this, "display", Toast.LENGTH_SHORT).show();  
} else {  
    Toast.makeText(MainActivity.this, "No show", Toast.LENGTH_SHORT).show();  

The disadvantage of this method is that as long as editText has focus, it is always true, but it is not that editText will pop up when it gets focus. No egg.

Because Google doesn't provide the relevant method to judge whether the soft keyboard pops up, it can only be solved by calculating the layout height:

private boolean isSoftShowing() {
  // Get the height of the current screen content
  int screenHeight = getWindow().getDecorView().getHeight();
  // Get the bottom of the View visible area
  Rect rect = new Rect();
  // DecorView is the top view of activity
  // Consider the case of virtual navigation bar (in the case of virtual navigation bar: screenHeight = rect.bottom + virtual navigation bar height)
  // Select screen height * 2 / 3 for judgment
  return screenHeight*2/3 > rect.bottom;

A clever way is to select 2 / 3 of the screen height to judge. If you think this is not reliable, you can also get the height of the virtual navigation bar to judge accordingly.

Attach how to get the navigation bar:

  * Height of the bottom virtual key bar 
  * @return 
  private int getSoftButtonsBarHeight() {  
      DisplayMetrics metrics = new DisplayMetrics();  
      // This method may not get the height of the real screen  
      int usableHeight = metrics.heightPixels;  
      // Get the real height of the current screen  
      int realHeight = metrics.heightPixels;  
      if (realHeight > usableHeight) {  
          return realHeight - usableHeight;  
      } else {  
          return 0;  




Topics: Google