Android 实现沉浸式状态栏终极大招---只需一个工具类

我自己封装好的工具类 直接拿来使用

步骤第一步
在build.gradle下面添加依赖
第三方库地址::https://github.com/jgilfelt/SystemBarTint
compile ‘com.readystatesoftware.systembartint:systembartint:1.0.3’
步骤第二步
直接在你的Activity中使用这个工具类

public class StatusBarUtil {
    public static void setStatusBarLayoutStyle(Context context,boolean isChange){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            ((AppCompatActivity)context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            ((AppCompatActivity)context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            SystemBarTintManager tintManager = new SystemBarTintManager(((AppCompatActivity)context));
            // 激活状态栏
            tintManager.setStatusBarTintEnabled(true);
            //判断是否需要更改状态栏颜色
            if(isChange){
                tintManager.setStatusBarTintResource(R.color.appMainColor);
            }else{
                tintManager.setStatusBarTintResource(android.R.color.white);
            }
            ViewGroup mContentView = (ViewGroup) ((AppCompatActivity) context).getWindow().findViewById(((AppCompatActivity) context).getWindow().ID_ANDROID_CONTENT);
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
                mChildView.setFitsSystemWindows(true);
            }
        }
    }
}

使用方式 StatusBarUtil.setStatusBarLayoutStyle(this,true or false);
在这里我想声明一下 为什么第二个参数 是TRUE或FALSE 因为有的不一致。APP 有的界面状态栏颜色 ,所以根据true 或 false 设置不同的颜色。

    ViewGroup mContentView = (ViewGroup) ((AppCompatActivity) context).getWindow().findViewById(((AppCompatActivity) context).getWindow().ID_ANDROID_CONTENT);
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
                mChildView.setFitsSystemWindows(true);

为什么在设置过程中我要加入以上代码 ,想必 大家都知道 要实现 沉浸式状态栏 就必须 在每个Activity根部局 添加

    android:clipToPadding="true"
    android:fitsSystemWindows="true"

这两行代码 ,为此我用了上述动态添加此设置的代码,避免了不必要的冗杂操作。
可能有的博友会问 ,添加这两行代码有什么用处呢 。
我就给大家解释一下
如果你不添加 这两行代码的话,即使你已经更改了状态栏的颜色,但是状态栏所占空间没有了,你的整体布局往上偏移了。写这两行代码 是保证状态栏 空间一直处于占据位置,不让其他组件占用。
如果还不懂得话 ,请查看我的另一个博客
https://blog.csdn.net/qq_21937107/article/details/80293557

你可能感兴趣的:(Android 实现沉浸式状态栏终极大招---只需一个工具类)