Android How to adjust layout in Full Screen Mode when softkeyboard is visible

前端 未结 25 1789
后悔当初
后悔当初 2020-11-22 03:56

I have researched a lot to adjust the layout when softkeyboard is active and I have successfully implemented it but the problem comes when I use android:theme=\"@andro

25条回答
  •  后悔当初
    2020-11-22 04:30

    1) Create KeyboardHeightHelper:

    public class KeyboardHeightHelper {
    
        private final View decorView;
        private int lastKeyboardHeight = -1;
    
        public KeyboardHeightHelper(Activity activity, View activityRootView, OnKeyboardHeightChangeListener listener) {
            this.decorView = activity.getWindow().getDecorView();
            activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
                int keyboardHeight = getKeyboardHeight();
                if (lastKeyboardHeight != keyboardHeight) {
                    lastKeyboardHeight = keyboardHeight;
                    listener.onKeyboardHeightChange(keyboardHeight);
                }
            });
        }
    
        private int getKeyboardHeight() {
            Rect rect = new Rect();
            decorView.getWindowVisibleDisplayFrame(rect);
            return decorView.getHeight() - rect.bottom;
        }
    
        public interface OnKeyboardHeightChangeListener {
            void onKeyboardHeightChange(int keyboardHeight);
        }
    }
    

    2) Let your activity be full screen:

    activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

    3) Listen for keyboard height changes and add bottom padding for your view:

    View rootView = activity.findViewById(R.id.root); // your root view or any other you want to resize
    KeyboardHeightHelper effectiveHeightHelper = new KeyboardHeightHelper(
            activity, 
            rootView,
            keyboardHeight -> rootView.setPadding(0, 0, 0, keyboardHeight));
    

    So, each time keyboard will appear on the screen - bottom padding for your view will change, and content will be rearranged.

提交回复
热议问题