Android 透明状态栏实现

来源:互联网 发布:香水知识 知乎 编辑:程序博客网 时间:2024/05/21 15:50

透明状态栏是Android4.4开始学习IOS系统的一种状态栏效果,主要就是让状态栏的背景色与Toolbar或者ActionBar实现相同的颜色衔接,或者实现页面头部的图片能顶状态栏顶部。
但是相信许多Android开发人员都会碰到一个问题,就是Android4.4上的实现问题,基本情况可以分为两种:

  1. 使用toolbar
  2. 不使用toolbar

1.使用Toolbar的情况

在实际应用中,我大概总结三种方式,都可以实现该效果:
(1)基本的做法就是在theme中添加

<item name="android:windowTranslucentStatus">true</item>

例如:

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">        <item name="android:windowTranslucentStatus">true</item>    </style>

但是这样做,在Android4.4中虽然可以将状态栏背景色与toolbar保持一致,但是这样做,其实也就是将toolbar直接顶到了状态栏上,因此就需要给状态栏添加一个paddingTop,值为25dp。并且需要在根布局上添加:android:fitsSystemWindows=”true”

(2)除了上面这种做法之外,在Android4.4中实现透明状态栏也可以使用下面的方式:

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

在BaseActivity中添加上述的代码,也可以在Android4.4中实现透明状态栏的情况。使用这种方式,则只需要给Toolbar添加一个paddingTop=“25dp”即可,而不需要做其他的操作。

(3)当上述两种情况均无法实现的时候,那么可以考虑这第三种情况:
基本的做法就是在theme中添加

<item name="android:windowTranslucentStatus">true</item>

例如:

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">        <item name="android:windowTranslucentStatus">true</item>    </style>

并且需要在根布局上添加android:fitsSystemWindows=”true”
另外,在代码中使用:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {    setTranslucentStatus(true);}setSystemBarTintManager(getActivity(),R.color.top_bar_normal_bg);

其中setTranslucentStatus和setSystemBarTintManager方法的代码:

    @TargetApi(19)    private void setTranslucentStatus(boolean on) {        Window win = getActivity().getWindow();        WindowManager.LayoutParams winParams = win.getAttributes();        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;        if (on) {            winParams.flags |= bits;        } else {            winParams.flags &= ~bits;        }        win.setAttributes(winParams);    }    protected void setSystemBarTintManager(Activity activity, int res){        SystemBarTintManager tintManager = new SystemBarTintManager(activity);        tintManager.setStatusBarTintEnabled(true);        tintManager.setStatusBarTintResource(res);    }

SystemBarTintManager 类是自己在网上找的一个类:
https://github.com/messnoTrace/SystemBarTintManager

第一次写博客,如果写的有点不好,大家请别介意,透明状态栏的使用,研究了多种的搭配实现,具体读者可以自己去做一些尝试,或者加我QQ,大家一起商量:306559652

原创粉丝点击