Android状态栏渐变色的实现

Android开发中在某些界面为了保证显示一致性,可能需要调整statusBar的背景色。Android 5.0开始只需要修改styles.xml文件中colorPrimaryDark的颜色值就可以修改statusbar背景色。但colorPrimaryDark只能设置固定色值的颜色,无法设置渐变色。所以,通过colorPrimaryDark无法实现状态栏的渐变色效果。

下面通过实现如下图1效果,举例具体说明。


方法一:(针对普通activity)

 

对于普通activity为实现上图从左上到右的渐变色,需要进行如下修改:

1.     此界面的activity对应的style中增加对windowBackground的设置,若style中有设置"android:statusBarColor"需要将此句删掉。

<style name="CalendarTheme" parent="android:Theme.Material.Light">

<itemname="android:colorPrimaryDark">#33000000</item>  为实现图1效果叠一层灰色

<item name="android:windowBackground">@drawable/tpv_window_background</item>

……

扫描二维码关注公众号,回复: 1998027 查看本文章

</style>

2.  Drawable下添加tpv_window_background.xml文件。

<?xmlversion="1.0"encoding="utf-8"?>

<layer-listxmlns:android="http://schemas.android.com/apk/res/android">

    <item

    android:drawable="@android:color/white"

       android:height="640dp"/>

    <item

        android:drawable="@drawable/tpv_statusbar_background"  设置状态栏颜色

        android:gravity="top"

        android:height="@dimen/statusbar_height"/>

</layer-list>

3.  Drawable下添加tpv_statusbar_background.xml文件。

<?xmlversion="1.0"encoding="utf-8"?>

<shapexmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">  定义状态栏颜色

   <gradient

        android:angle="315"

        android:startColor="@color/left_top"

        android:endColor="@color/right_bottom"/>

</shape>

上述方法是只对普通的Activity有效,若是AppCompatActivity使用上述的方法无法实现状态栏的渐变效果。

方法二:(针对AppCompatActivity)

 

AppCompatActivity需要使用Toolbar来替代ActionBar实现状态栏渐变的效果。

1. 去/res/values/styles.xml里找到你activity或者application使用的theme,theme

一定要使用NoActionBar的随便一种;

2.  在你的activity的oncreate中或是setContentView下边执行如下代码:

//当前手机版本为Android 5.0及以上

if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.L) {

            View decorView = getWindow().getDecorView();

            intoption = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;

            decorView.setSystemUiVisibility(option);

           getWindow().setStatusBarColor(Color.TRANSPARENT);

}

3.  使用Toolbar来替代ActionBar,但toolbar高度需要设置为actionbar和statusbar高度的总和。

<android.support.v7.widget.Toolbar

        android:id="@+id/toolbar"

        android:layout_width="match_parent"

        android:layout_height="@dimen/statusbar_and_actionbar_height"      注意toolbar高度 

        android:background="@drawable/tpv_statusbar_background">

 

        ……

<ImageView

                android:id="@+id/top_status_bar"

               android:layout_width="match_parent"  为实现图1效果叠一层灰色 

               android:layout_height="@dimen/status_bar_height"

                android:background="#33000000"/>

       ……

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

    备注,其中tpv_statusbar_background.xml定义的是statusbar的渐变色颜色,与方法一中定义的一样。

  综合上述,可根据界面所要的效果实现状态栏的渐变色效果。

猜你喜欢

转载自blog.csdn.net/qq_25749749/article/details/80901313
今日推荐