How to check visibility of software keyboard in Android?

前端 未结 30 4547
半阙折子戏
半阙折子戏 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条回答
  •  猫巷女王i
    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);
        }
    }
    

提交回复
热议问题