关于Android5.0透明状态栏高度适配(沉浸式状态栏)

Github 例子 ps:提供状态栏导航栏操作

例子

SystemUiHelper.get(activity)
    .setStatusBarColor(0)
    .setNavigationBarColor(0x33ffffff)
    .setLightStatusBar()
    .setLightNavigationBar()
    .fullScreen()
    .systemUiHeight(new SystemUiAttrCallback() {
        @override
        public void windowPaddingSize(int left, int top, int right, int bottom) {
        }
    });

前言

距离Android5.0诞生已经很长一段时间了,透明状态栏也不再新鲜,但是还是有很多人不知道如何获取状态栏的高度进行适配屏幕,所以写一篇文章普及下。(国内称之为沉浸式状态栏,这个说法是错的)

正文

相信大多人都知道,状态栏的高度是通过Padding进行设置的,这篇文章主要就是介绍如何获取这个Padding的高度。
所有View的展示都离不开WindowInsets类,没错,就是这个类记录了状态栏的高度,只要获取到DecorViewWindowInsets,我们就能获取到状态栏的高度

/**
 * Describes a set of insets for window content.
 *
 * 

WindowInsets are immutable and may be expanded to include more inset types in the future. * To adjust insets, use one of the supplied clone methods to obtain a new WindowInsets instance * with the adjusted properties.

* * @see View.OnApplyWindowInsetsListener * @see View#onApplyWindowInsets(WindowInsets) */ public final class WindowInsets { *** }

我们可以通过获取DecorView通过设置监听来获取WindowInsets

{
        getWindow().getDecorView().setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @Override
            public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                insets.getSystemWindowInsetTop();//这就是状态栏高度
                //获取高度后的处理
                return v.onApplyWindowInsets(insets);//此函数必须调用,否则WindowInsets无效
            }
        });
}

监听返回需调用onApplyWindowInsets函数,通过源码可以看到,不设置监听时是调用了onApplyWindowInsets函数的,设置监听后就没有调用了,不调用该函数会使得WindowInsets无法正确配置

public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
        try {
            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
            } else {
                return onApplyWindowInsets(insets);
            }
        } finally {
            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
        }
    }

你可能感兴趣的:(关于Android5.0透明状态栏高度适配(沉浸式状态栏))