三步实现沉浸式状态栏

沉浸式是android 4.4之后推出的新型手机屏幕显示效果,沉浸式可以将手机状态栏和导航栏颜色调整为与应用颜色一样或者一致,让应用更加美观。

网上看了很多例子,有的要判断机型,有的需要另外设置bar的高度,其实不需要(因为有第三方),三步实现沉浸式状态栏。浅色状态栏黑色字体模式的话看下面的参考。

原理:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

看效果

《三步实现沉浸式状态栏》 小米安卓6.0系统
《三步实现沉浸式状态栏》 华为安卓4.4系统

第一步:

添加依赖,这里我用SystemBarTint
另外一个库也可以 https://github.com/laobie/StatusBarUtil

dependencies {

    /*状态栏着色 https://github.com/jgilfelt/SystemBarTint*/
    compile 'com.readystatesoftware.systembartint:systembartint:1.0.4'
}
第二步:

xml根布局添加

android:fitsSystemWindows="true"
第三步:

在BaseActivity编写公共方法

/**
 * @创建 HaiJia
 * @时间 2017/4/18 9:47
 * @描述 BaseActivity 
 */

public abstract class BaseActivity extends AppCompatActivity {

    private View mContextView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContextView = LayoutInflater.from(this)
                .inflate(bindLayout(), null);
        setContentView(mContextView);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        initSystemBarTint();
        initData();
        initView(mContextView);
        initAction();
   
    }

    /**
     * [绑定布局]
     *
     * @return
     */
    public abstract int bindLayout();

    /**
     * [初始化控件]
     *
     * @param view
     */
    public abstract void initView(final View view);


    /**
     * [初始化数据]
     *
     * 获取页面传过来的值以及初始化一些数据
     */
    public abstract void initData();

    /**
     * [初始化数据]
     *
     * 初始化View之后的一些操作
     */
    public abstract void initAction();



    /**
     * [设置状态栏颜色]
     *
     * 初始化状态栏
     */
    protected void initSystemBarTint() {

        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ) {//大于4.4版本

            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            //主题颜色
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            //是否设置状态栏颜色
            tintManager.setStatusBarTintEnabled(true);
            //这里调用需要的通知栏颜色
            tintManager.setStatusBarTintResource(R.color.primary);
            
        }else{
            //("不可设置状态栏");
        }
    }
参考文章

Android沉浸式UI实现及原理
白底黑字!Android浅色状态栏黑色字体模式
Android 6.0状态栏使用灰色文字和图标

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