沉浸式状态栏

来源:互联网 发布:fifaonline316普卡数据 编辑:程序博客网 时间:2024/06/05 11:49

转自:https://juejin.im/post/5a25f6146fb9a0452405ad5b

由于沉浸式状态栏设置是在Android 4.4之后才提供的,所以我们需要对Android 4.4以上的系统做适配。Android 4.4有两种方式可以实现沉浸式状态栏,一种是在资源文件中设置,一种是在代码中设置。

1、资源文件中设置沉浸式状态栏

首先,我们要修改values/styles.xml,在里面添加一个空的style,继承自BaseTheme。

<resources>    <!-- Base application theme. -->    <style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">        <!-- Customize your theme here. -->        <item name="colorPrimary">@color/colorPrimary</item>        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>        <item name="colorAccent">@color/colorAccent</item>    </style>    <style name="AppTheme" parent="BaseTheme" /></resources>

然后在values-v19目录下的styles.xml文件(如果项目中没有就新建一个,在4.4以上的系统就会读取该目录下的资源文件)添加如下代码:

<resources>    <style name="AppTheme" parent="BaseTheme">        <item name="android:windowTranslucentStatus">true</item>    </style></resources>

然后将App的主题设置为AppTheme即可。 注:android:windowTranslucentStatus这个属性是v19开始引入的。

2、在代码中设置

在代码中实现更为方便一点,我们只需要在BaseActivity中添加一个FLAG_TRANSLUCENT_STATUS的flag即可

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);}

通过上述两种方法设置之后,效果图如下:
这里写图片描述

解决toolbar覆盖状态栏的问题,可以将toolbar的高度设置为其原始高度加上statuBar的高度,然后给toolbar的顶部设置个padding值,大小为statuBar的高度:

//处理toolbar覆盖状态栏    protected void setToolbarPadding() {        if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.KITKAT) {            if (mToolbar != null) {                int oldToolbarHeight = mToolbar.getLayoutParams().height;                int statusBarHeight = BarUtils.getStatusBarHeight();                mToolbar.setPadding(mToolbar.getPaddingLeft(), statusBarHeight, mToolbar.getPaddingRight(),                        mToolbar.getPaddingBottom());                mToolbar.getLayoutParams().height = statusBarHeight + oldToolbarHeight;            }        }    }
  /**     * 获取状态栏高度(px)     *     * @return 状态栏高度     */    public static int getStatusBarHeight() {        Resources resources = Utils.getContext().getResources();        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");        return resources.getDimensionPixelSize(resourceId);    }

再运行,效果如下(5.0+的手机):
这里写图片描述

解决状态栏阴影覆盖的问题:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);            getWindow().setStatusBarColor(Color.TRANSPARENT);        }

在运行ok:
这里写图片描述

原创粉丝点击