How to check visibility of software keyboard in Android?

前端 未结 30 4420
半阙折子戏
半阙折子戏 2020-11-21 04:43

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

30条回答
  •  误落风尘
    2020-11-21 05:30

    None of these solutions will work for Lollipop as is. In Lollipop activityRootView.getRootView().getHeight() includes the height of the button bar, while measuring the view does not. I've adapted the best/simplest solution above to work with Lollipop.

        final View activityRootView = findViewById(R.id.activityRoot);
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
      @Override
      public void onGlobalLayout() {
        Rect r = new Rect();
        //r will be populated with the coordinates of your view that area still visible.
        activityRootView.getWindowVisibleDisplayFrame(r);
    
        int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
        Resources res = getResources();
        // The status bar is 25dp, use 50dp for assurance
        float maxDiff =
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, res.getDisplayMetrics());
    
        //Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          float buttonBarHeight =
              TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, res.getDisplayMetrics());
          maxDiff += buttonBarHeight;
        }
        if (heightDiff > maxDiff) { // if more than 100 pixels, its probably a keyboard...
          ...do something here
        }
      }
    });
    

提交回复
热议问题