How to capture the “virtual keyboard show/hide” event in Android?

前端 未结 16 1198
暗喜
暗喜 2020-11-22 07:23

I would like to alter the layout based on whether the virtual keyboard is shown or not. I\'ve searched the API and various blogs but can\'t seem to find anything useful.

16条回答
  •  感情败类
    2020-11-22 07:55

    Like @amalBit's answer, register a listener to global layout and calculate the difference of dectorView's visible bottom and its proposed bottom, if the difference is bigger than some value(guessed IME's height), we think IME is up:

        final EditText edit = (EditText) findViewById(R.id.edittext);
        edit.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (keyboardShown(edit.getRootView())) {
                    Log.d("keyboard", "keyboard UP");
                } else {
                    Log.d("keyboard", "keyboard Down");
                }
            }
        });
    
    private boolean keyboardShown(View rootView) {
    
        final int softKeyboardHeight = 100;
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
        int heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > softKeyboardHeight * dm.density;
    }
    

    the height threshold 100 is the guessed minimum height of IME.

    This works for both adjustPan and adjustResize.

提交回复
热议问题