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

前端 未结 16 1211
暗喜
暗喜 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 08:17

    This may not be the most effective solution. But this worked for me every time... I call this function where ever i need to listen to the softKeyboard.

    boolean isOpened = false;
    
    public void setListenerToRootView() {
        final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
    
                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
                if (heightDiff > 100) { // 99% of the time the height diff will be due to a keyboard.
                    Toast.makeText(getApplicationContext(), "Gotcha!!! softKeyboardup", 0).show();
    
                    if (isOpened == false) {
                        //Do two things, make the view top visible and the editText smaller
                    }
                    isOpened = true;
                } else if (isOpened == true) {
                    Toast.makeText(getApplicationContext(), "softkeyborad Down!!!", 0).show();
                    isOpened = false;
                }
            }
        });
    }
    

    Note: This approach will cause issues if the user uses a floating keyboard.

提交回复
热议问题