How to check visibility of software keyboard in Android?

前端 未结 30 4424
半阙折子戏
半阙折子戏 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:17

    Some improvements to avoid wrongly detect the visibility of soft keyboard on high density devices:

    1. Threshold of height difference should be defined as 128 dp, not 128 pixels.
      Refer to Google design doc about Metrics and Grid, 48 dp is comfortable size for touch object and 32 dp is minimum for buttons. Generic soft keyboard should include 4 rows of key buttons, so minimum keyboard height should be: 32 dp * 4 = 128 dp, that means threshold size should transfer to pixels by multiply device density. For xxxhdpi devices (density 4), the soft keyboard height threshold should be 128 * 4 = 512 pixels.

    2. Height difference between root view and its visible area:
      root view height - status bar height - visible frame height = root view bottom - visible frame bottom, since status bar height equal to the top of root view visible frame.

      private final String TAG = "TextEditor";
      private TextView mTextEditor;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_editor);
          mTextEditor = (TextView) findViewById(R.id.text_editor);
          mTextEditor.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
              @Override
              public void onGlobalLayout() {
                  isKeyboardShown(mTextEditor.getRootView());
              }
          });
      }
      
      private boolean isKeyboardShown(View rootView) {
          /* 128dp = 32dp * 4, minimum button height 32dp and generic 4 rows soft keyboard */
          final int SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD = 128;
      
          Rect r = new Rect();
          rootView.getWindowVisibleDisplayFrame(r);
          DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
          /* heightDiff = rootView height - status bar height (r.top) - visible frame height (r.bottom - r.top) */
          int heightDiff = rootView.getBottom() - r.bottom;
          /* Threshold size: dp to pixels, multiply with display density */
          boolean isKeyboardShown = heightDiff > SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD * dm.density;
      
          Log.d(TAG, "isKeyboardShown ? " + isKeyboardShown + ", heightDiff:" + heightDiff + ", density:" + dm.density
                  + "root view height:" + rootView.getHeight() + ", rect:" + r);
      
          return isKeyboardShown;
      }
      
    0 讨论(0)
  • 2020-11-21 05:18

    You can observe softkeyboard's hide by using activity's decorView.

    public final class SoftKeyboardUtil {
        public static final String TAG = "SoftKeyboardUtil";
        public static void observeSoftKeyBoard(Activity activity , final OnSoftKeyBoardHideListener listener){
            final View decorView = activity.getWindow().getDecorView();
            decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Rect rect = new Rect();
                    decorView.getWindowVisibleDisplayFrame(rect);
                    int displayHight = rect.bottom - rect.top;
                    int hight = decorView.getHeight();
                    boolean hide = (double)displayHight / hight > 0.8 ;
                    if(Log.isLoggable(TAG, Log.DEBUG)){
                        Log.d(TAG ,"DecorView display hight = "+displayHight);
                        Log.d(TAG ,"DecorView hight = "+ hight);
                        Log.d(TAG, "softkeyboard visible = " + !hide);
                    }
    
                    listener.onSoftKeyBoardVisible(!hide);
    
                }
            });
        }
    
    
    
        public interface OnSoftKeyBoardHideListener{
            void onSoftKeyBoardVisible(boolean visible);
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:18

    It has been forever in terms of the computer but this question is still unbelievably relevant! So I've taken the above answers and have combined and refined them a bit...

    public interface OnKeyboardVisibilityListener {
        void onVisibilityChanged(boolean visible);
    }
    
    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
        final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    
            private boolean wasOpened;
    
        private final Rect r = new Rect();
    
            @Override
            public void onGlobalLayout() {
                activityRootView.getWindowVisibleDisplayFrame(r);
    
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                boolean isOpen = heightDiff > 100;
                if (isOpen == wasOpened) {
                    logDebug("Ignoring global layout change...");
                    return;
                }
    
                wasOpened = isOpen;
                listener.onVisibilityChanged(isOpen);
            }
        });
    }
    

    It works for me.

    0 讨论(0)
  • 2020-11-21 05:18

    Don't make any hard code. Best way is you have to resize your views while on Get Focus on EditText with KeyBord Show. You can do this adding resize property on activity into Manifest file using below code.

    android:windowSoftInputMode="adjustResize"

    0 讨论(0)
  • 2020-11-21 05:21

    Checking the height of elements is not reliable because some keyboards like WifiKeyboard have zero height.

    Instead, you can use the callback result of showSoftInput() and hideSoftInput() to check for the status of the keyboard. Full details and example code at

    https://rogerkeays.com/how-to-check-if-the-software-keyboard-is-shown-in-android

    0 讨论(0)
  • 2020-11-21 05:21

    The idea is, if you need to hide your keyboard and check soft input state at the same time, use the following solution:

    public boolean hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        return imm.hideSoftInputFromWindow(mViewPager.getWindowToken(), 0);
    }
    

    This method returns true if keyboard was shown before hiding.

    0 讨论(0)
提交回复
热议问题