导航栏遮挡布局的一种解决方案

在android 11 的部分手机,出现导航栏遮挡布局的问题,我们使用下面的方法解决了问题:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            StatusBarUtil.isNavigationBarExist(
                this
            ) { isShowing, height ->
                if (isShowing) {
                    window.decorView.findViewById<View>(android.R.id.content)
                        .setPadding(0, 0, 0, height);
                } else {
                    window.decorView.findViewById<View>(android.R.id.content)
                        .setPadding(0, 0, 0, 0);
                }
            }
        }
 /**
     * 获取底部导航栏高度
     */
    public static int getNavigationHeight(Context activity) {
        if (activity == null) {
            return 0;
        }
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height",
                "dimen", "android");
        int height = 0;
        if (resourceId > 0) {
            //获取NavigationBar的高度
            height = resources.getDimensionPixelSize(resourceId);
        }
        return height;
    }

    /**
     * 判断及监听底部导航栏高度
     */
    public static void isNavigationBarExist(Activity activity, final OnNavigationStateListener onNavigationStateListener) {
        if (activity == null) {
            return;
        }
        final int height = getNavigationHeight(activity);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            activity.getWindow().getDecorView().setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                @Override
                public WindowInsets onApplyWindowInsets(View v, WindowInsets windowInsets) {
                    boolean isShowing = false;
                    int bottom = 0;
                    if (windowInsets != null) {
                        bottom = windowInsets.getSystemWindowInsetBottom();
                        isShowing = (bottom == height);
                    }
                    if (onNavigationStateListener != null && bottom <= height) {
                        onNavigationStateListener.onNavigationState(isShowing, bottom);
                    }
                    return windowInsets;
                }
            });
        }
    }

    public interface OnNavigationStateListener {
        void onNavigationState(boolean isShowing, int bottom);
    }

你可能感兴趣的:(Android,android,java,android,studio)