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

前端 未结 30 1869
情书的邮戳
情书的邮戳 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:54

    Very Easy

    1. Put id on your root view

    rootView is just a view pointing to my root view in this case a relative layout:

    
    

    2. Initialize your root view in your Activity:

    RelativeLayout rootView = (RelativeLayout) findViewById(R.id.addresses_confirm_root_view);

    3. Detect if keyboard is opened or closed by using getViewTreeObserver()

        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    int heightDiff = rootView.getRootView().getHeight() - rootView.getHeight();
    
                    if (heightDiff > 100) { 
                        Log.e("MyActivity", "keyboard opened");
                    } else { 
                        Log.e("MyActivity", "keyboard closed");
                    }
                }
            });
    

提交回复
热议问题