设置Android状态栏的颜色

1. 前言

现在的APP为了提高界面美观,会根据界面整体的风格,调整状态栏的颜色。但是由于安卓系统版本众多,有谷歌Android、小米MIUI、华为EMUI等等,而且对于设置状态栏的颜色还没有一个统一标准,所以适配起来是一件很麻烦的事情。通过查询资料,我汇总了一些方法,封装了一个工具类StatusBarUtils。

2. 工具类

package com.fantasy.utils.ui;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 状态栏工具类
 * <pre>
 *     author  : Fantasy
 *     version : 1.0, 2018-12-10
 *     since   : 1.0, 2018-12-10
 * </pre>
 */
public class StatusBarUtils {

    /**
     * 获取状态栏的高度,有可能获取到的大小为0
     *
     * @param context 上下文
     * @return 高度,单位为像素
     */
    public static int getHeight(Context context) {
        int height = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = context.getResources().getDimensionPixelSize(resourceId);
        }
        return height;
    }

    /**
     * 设置状态栏颜色,支持4.4以上版本
     *
     * @param activity 活动
     * @param colorId  颜色值
     */
    public static void setColor(Activity activity, int colorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.setStatusBarColor(activity.getResources().getColor(colorId));
        }
//        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            // 使用第三方库 SystemBarTint 可以让4.4版本状态栏变色,但需要先将状态栏设置为透明
//            // com.readystatesoftware.systembartint:systembartint:1.0.3
//            useTransparentMode(activity);
//            SystemBarTintManager tintManager = new SystemBarTintManager(activity);
//            tintManager.setStatusBarTintEnabled(true);
//            tintManager.setStatusBarTintResource(colorId);
//        }
    }

    /**
     * 使用透明状态栏
     *
     * @param activity 活动
     */
    public static void useTransparentMode(Activity activity) {
        Window window = activity.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            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.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 使用亮色状态栏,黑色文字和图标
     * 适配4.4以上版本MIUI、Flyme和Android 6.0及以上
     *
     * @param activity 活动
     * @return 1:MIUI 2:Flyme 3:Android 6.0
     */
    public static int useLightMode(Activity activity) {
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (useMIUILightMode(activity, true)) {
                result = 1;
            } else if (useFlymeLightMode(activity.getWindow(), true)) {
                result = 2;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 设置状态栏文字深色,同时保留之前的flag
                int originFlag = activity.getWindow().getDecorView().getSystemUiVisibility();
                activity.getWindow().getDecorView().setSystemUiVisibility(originFlag
                        | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

                //activity.getWindow().getDecorView().setSystemUiVisibility(
                //        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                result = 3;
            }
        }
        return result;
    }

    /**
     * 已知系统类型时,使用亮色状态栏,黑色文字和图标
     * 适配4.4以上版本MIUI、Flyme和Android 6.0及以上
     *
     * @param activity 活动
     * @param type     1:MIUI 2:Flyme 3:Android6.0
     */
    public static void useLightMode(Activity activity, int type) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (type == 1) {
                useMIUILightMode(activity, true);
            } else if (type == 2) {
                useFlymeLightMode(activity.getWindow(), true);
            } else if (type == 3) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 设置状态栏文字深色,同时保留之前的flag
                    int originFlag = activity.getWindow().getDecorView().getSystemUiVisibility();
                    activity.getWindow().getDecorView().setSystemUiVisibility(originFlag
                            | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

                    //activity.getWindow().getDecorView().setSystemUiVisibility(
                    //        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                }
            }
        }
    }

    /**
     * 已知系统类型时,使用暗色状态栏,清除黑色文字和图标效果
     * 适配4.4以上版本MIUI、Flyme和Android 6.0及以上
     *
     * @param activity 活动
     * @param type     1:MIUI 2:Flyme 3:Android6.0
     */
    public static void useDarkMode(Activity activity, int type) {
        if (type == 1) {
            useMIUILightMode(activity, false);
        } else if (type == 2) {
            useFlymeLightMode(activity.getWindow(), false);
        } else if (type == 3) {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

            // 清除状态栏文字深色,同时保留之前的flag
            //int originFlag = activity.getWindow().getDecorView().getSystemUiVisibility();
            // 使用异或清除SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            //activity.getWindow().getDecorView().setSystemUiVisibility(originFlag
            //        ^ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏文字及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    private static boolean useFlymeLightMode(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;
    }

    /**
     * 需要MIUI 6以上
     *
     * @param activity 活动
     * @param dark     是否把状态栏文字及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    private static boolean useMIUILightMode(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) {
            }
        }
        return result;
    }

}

3. 如何使用

我提供的工具类默认是只支持5.0及以上版本,如果还想兼容到4.4的话,可以把setColor()方法里面的注释去掉,使用第三方库 SystemBarTint ,如下所示:

    /**
     * 设置状态栏颜色,支持4.4以上版本
     *
     * @param activity 活动
     * @param colorId  颜色值
     */
    public static void setColor(Activity activity, int colorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.setStatusBarColor(activity.getResources().getColor(colorId));
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 使用第三方库 SystemBarTint 可以让4.4版本状态栏变色,但需要先将状态栏设置为透明
            // com.readystatesoftware.systembartint:systembartint:1.0.3
            useTransparentMode(activity);
            SystemBarTintManager tintManager = new SystemBarTintManager(activity);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(colorId);
        }
    }

3.1 使用亮色状态栏,黑色文字和图标

这里以“白色状态栏”为例,具体如下:

// 白色状态栏
// 同时需要在布局文件中的根布局加上android:fitsSystemWindows="true"
// 因为不加的话,小米手机会呈现出全屏状态,界面会顶到最上面,会被状态栏遮住
StatusBarUtils.useLightMode(this);
StatusBarUtils.setColor(this, R.color.white);

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

</RelativeLayout>

3.2 使用暗色状态栏,白色文字和图标

这里以“红色状态栏”为例,具体如下:

StatusBarUtils.setColor(this, R.color.red);
发布了43 篇原创文章 · 获赞 34 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/Fantasy_Lin_/article/details/84941514
今日推荐