Android 沉浸式状态栏适配方案

首先说下什么是沉浸式状态栏:这是android4.4以后开始支持的一种效果,状态栏不再是一个黑条,而是置为透明或者半透明,然后页面延伸到状态栏下面,这样状态栏区域也可以成为app页面显示区域的一部分,提升了界面的完整性。

《Android 沉浸式状态栏适配方案》

但是因为android碎块化的问题,如何保证沉浸式状态栏在各种屏幕尺寸和系统版本上显示效果的一致性,是个挺繁琐的事儿。在此讲解下我们在适配沉浸式状态栏的方法和问题解决办法。

让activity支持沉浸式可以通过设置Theme属性或者直接在activity中添加flag实现

1.设置 Theme 主题设置状态栏沉浸

在我们的res里新建一个values-v19(对应android4.4以上)文件夹,文件夹里再创建个styles.xml ,values和values-v19里styles.xml中设置同名主题,但是values-v19里主题多一个android:windowTranslucentStatus属性,示例如下:

 <!--values-->
    <style name="TranslucentStatusTheme" parent="AppTheme.NoActionBar">
    </style>

    <!--values-19。v19开始有android:windowTranslucentStatus这个属性,这个属性为将状态-->
    <style name="TranslucentStatusTheme" parent="AppTheme.NoActionBar">
        <item name="android:windowTranslucentStatus">true</item>
    </style>

    <!--values-21。v19开始有android:windowTranslucentStatus这个属性-->
    <!--<style name="TranslucentStatusTheme" parent="AppTheme.NoActionBar">
         <item name="android:windowTranslucentStatus">false</item>
         <item name="android:windowTranslucentNavigation">true</item>
         <item name="android:windowDrawsSystemBarBackgrounds">true</item>
         Android 5.x开始需要把颜色设置透明,否则导航栏会呈现系统默认的浅灰色
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>-->

之后我们在AndroidManifest.xml中为activity添加上该Theme,这个activity就会将界面延伸入状态栏:

<activity
    android:name=".NotificationActivity"
    android:label="@string/title_activity_notification"
    android:theme="@style/TranslucentStatusTheme" />

这里我还注释掉了一个values-v21下的主题,这是网上很多见的一个适配方案,
但是这个其实是错误的!
android5.0以上提供了android:statusBarColor属性,可以设置状态栏颜色,设置android:statusBarColor时,android:windowTranslucentStatus必须为false,二者不会同时生效。但是这个属性并不会让页面向上延伸。google设置这个属性,只是因为他们推荐我们将状态栏自定义为符合设计指南的颜色,并不是对沉浸式的支持升级。
上面那个21的Theme也能将页面实现沉浸式,而是靠android:windowTranslucentNavigation生效的,这样做会有别的大坑,后面会讲。

2.代码中设置状态栏沉浸

直接在activity的onCreate中设置:

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

 
设置完状态栏沉浸之后,APP界面就已经铺满全屏了,但是正常情况下,我们需要APP的内容展示和可操作区域还是在状态栏以下的位置开始计算的。所以我们还要在布局中做下调整,保证内容还是在状态栏下面,一般在布局中设置android:fitsSystemWindows=”true”。就可以了

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".dialog.DialogActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_dialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:fitsSystemWindows="true">
        <ImageView
            android:id="@+id/iv_back"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_margin="8dp"
            android:background="?android:attr/actionBarItemBackground"
            android:clickable="true"
            android:scaleType="centerInside"
            android:src="@mipmap/ic_launcher" />


        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ... ...
            />

    </android.support.v7.widget.Toolbar>
    
    ... ...
    
</FrameLayout>

android:fitsSystemWindows是layout的属性,其效果是,设置沉浸式之后,android:fitsSystemWindows = true的layout会被赋予一个跟状态栏等高的paddingTop,用于填充状态栏。
为什么在toolbar上设置android:fitsSystemWindows = true而不是最底层布局?因为当多层布局设置了android:fitsSystemWindows = true时,只有最底层的layout有效果。而在有title的布局中,我们一般是需要状态栏跟title的底色一致的,所以我们把android:fitsSystemWindows = true放在toolbar上,这样toolbar多出来的paddingTop就刚好占在状态栏的位置。
最后效果就是这样的:

《Android 沉浸式状态栏适配方案》

有时候我们不光是要页面延伸到状态栏,甚至有时候需要延伸到屏幕下方虚拟按键区的导航栏,这时候就用到我们刚才上面看到的android:windowTranslucentNavigation属性,顾名思义,就是将导航栏半透明,并会实现沉浸式效果。很有意思的是,设置android:windowTranslucentNavigation为true之后,即使状态栏没有置为半透明,界面也会沉入到状态栏底下。

《Android 沉浸式状态栏适配方案》

这时候我们会发现另一个问题,设置了android:fitsSystemWindows = true的layout不但多了paddingTop来填充状态栏,还多了一个跟导航栏等高的paddingButtom,这样一来title又变型了,如果页面没有title,直接把android:fitsSystemWindows = true放在最底布局也就无所谓了,但是如果要保留title怎么办?

在这里,我们通过去掉android:fitsSystemWindows = true,然后在代码中手动添加paddingTop的办法来处理:

 @Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frame);
        
        //注意4.4以下是不支持沉浸式状态栏的,所以不要添加paddingTop了
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Toolbar titlebar = findViewById(R.id.toolbar);
            titlebar.setPadding(0, getStatusBarHeight(this), 0, 0);
        }

        ... ...
 }

    /**
     * 通过反射获取状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

效果如图:

《Android 沉浸式状态栏适配方案》

以上基本就足以适配绝大多数情况了。

设置纯透明状态栏以及设置深色状态栏文字

找到了通过setSystemUiVisibility()将状态栏设置为全透明的方法,不会填充导航栏,但只支持在代码中设置,无法通过设置主题实现,同时,通过setSystemUiVisibility()我们还可以改变状态栏文字颜色。

public class StatusBarUtil {
    private static final int MIUI = 1;
    private static final int FLYME = 2;
    private static final int ANDROID_M = 3;

    /**
     * 修改状态栏为全透明且不占位
     */
    @TargetApi(19)
    public static void transparencyBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            //windowTranslucentStatus、windowTranslucentNavigation,都可以触发LAYOUT_FULLSCREEN 、LAYOUT_STABLE
            //但是状态栏只会变成半透明,要设置全透明必须用FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS和setStatusBarColor,但是windowTranslucentStatus=true时不会生效。
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN: 使状态栏出现的时候,不会重新调整activity的高度,状态栏覆盖在activity之上。
            //SYSTEM_UI_FLAG_LAYOUT_STABLE: 让应用的主体内容占用系统状态栏的空间
            //这俩好像只能在代码里设置
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }


    /**
     * 利用反射获取状态栏高度
     */
    private static int getStatusBarHeight(Activity activity) {
        int result = 0;
        //获取状态栏高度的资源id
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 状态栏亮色模式,设置状态栏黑色文字、图标,
     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
     *
     * @return 1:MIUUI 2:Flyme 3:android6.0
     */
    public static int setStatusBarLightMode(Activity activity) {
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (MIUISetStatusBarLightMode(activity, true)) {
                result = MIUI;
            } else if (FLYMESetStatusBarLightMode(activity.getWindow(), true)) {
                result = FLYME;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                result = ANDROID_M;
            }
        }
        return result;
    }

    /**
     * 已知系统类型时,设置状态栏黑色文字、图标。
     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
     *
     * @param type 1:MIUUI 2:Flyme 3:android6.0
     */
    public static void setStatusBarLightMode(Activity activity, int type) {
        if (type == MIUI) {
            MIUISetStatusBarLightMode(activity, true);
        } else if (type == FLYME) {
            FLYMESetStatusBarLightMode(activity.getWindow(), true);
        } else if (type == ANDROID_M) {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    /**
     * 状态栏暗色模式,清除MIUI、flyme或6.0以上版本状态栏黑色文字、图标
     */
    public static void setStatusBarDarkMode(Activity activity, int type) {
        if (type == MIUI) {
            MIUISetStatusBarLightMode(activity, false);
        } else if (type == FLYME) {
            FLYMESetStatusBarLightMode(activity.getWindow(), false);
        } else if (type == ANDROID_M) {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏文字及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    private static boolean FLYMESetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    /**
     * 需要MIUIV6以上
     *
     * @param dark 是否把状态栏文字及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    private static boolean MIUISetStatusBarLightMode(Activity activity, boolean dark) {
        boolean result = false;
        Window window = activity.getWindow();
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //开发版 7.7.13 及以后版本采用了系统API,旧方法无效但不会报错,所以两个方式都要加上
                    if (dark) {
                        activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    } else {
                        activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

折叠布局处理

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ... ...>

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="280dp"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            ... ... >

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:src="@drawable/biscuits"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                ... ... />
        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

我们实现折叠布局的时候,真正展示的其实主要是AppBarLayout,CollapsingToolbarLayout其实主要是对AppBarLayout的拓展,所以把android:fitsSystemWindows=”true”放在AppBarLayout上就可以。此外我还发现个问题,
android4.4对AppBarLayout支持有问题,会出现CollapsingToolbarLayout里的内容无法填充状态栏的情况,

《Android 沉浸式状态栏适配方案》

对此,建议将用作背景的图片不要放在CollapsingToolbarLayout里了,直接作为AppBarLayout的背景,这样就能完美解决。

《Android 沉浸式状态栏适配方案》

以上大都基于个人的实践总结,可能对有些API的理解有误差,欢迎更清楚的大牛们在评论中指正。

    原文作者:kmf_jaad
    原文地址: https://www.jianshu.com/p/2fa0095aedc3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞