How do I detect if software keyboard is visible on Android Device or not?

前端 未结 30 1865
情书的邮戳
情书的邮戳 2020-11-22 10:59

Is there a way in Android to detect if the software (a.k.a. \"soft\") keyboard is visible on screen?

30条回答
  •  春和景丽
    2020-11-22 11:33

    Answer of @iWantScala is great but not working for me
    rootView.getRootView().getHeight() always has the same value

    one way is to define two vars

    private int maxRootViewHeight = 0;
    private int currentRootViewHeight = 0;
    

    add global listener

    rootView.getViewTreeObserver()
        .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                currentRootViewHeight = rootView.getHeight();
                if (currentRootViewHeight > maxRootViewHeight) {
                    maxRootViewHeight = currentRootViewHeight;
                }
            }
        });
    

    then check

    if (currentRootViewHeight >= maxRootViewHeight) {
        // Keyboard is hidden
    } else {
        // Keyboard is shown
    }
    

    works fine

提交回复
热议问题