透明状态栏 transparent status bar

iOS系统中,任何一个界面的状态栏都是和紧贴着状态栏的界面使用相同的颜色,这无疑非常的美观,在Android系统中,也要搞出同样的效果,应该怎么做呢……

  • 准备工作

首先,我们要确认我们现在操作的主题是否能够完成任务。

  1. style.xml文件中,当前应用的主题应是*.NoActionBar,因为ActionBar这东西实在是烦人,只要有它,透明效果就做不出来,而且谷歌官方也觉得这东西没什么意思推荐使用toolBar代替。
  • 正式开始

原理

透明式状态栏的原理就是将状态栏的颜色设为透明色,并将状态栏下方的页面伸展到状态栏位置,展现出没有颜色相同的一体式界面。

代码

  • 首先在Activity对应的类里的onCreate()函数里,加几句话。
    onCreate()
protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Window window = getWindow();
        //设置让layout全屏显示
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        //设置让状态栏颜色为透明
        window.setStatusBarColor(Color.TRANSPARENT);
    }
  • 相应的,在Activity对应的布局文件里,根元素添加一个属性:
//此属性能确保当layout全屏的时候,能给状态栏留个位置,不至于状态栏和layout内容重叠
android:fitsSystemWindows="true"
  • 还是同一个文件,我们要设置一下整个layout的背景颜色。因为设置了android:fitsSystemWindows="true",所以只有背景颜色才能延伸到状态栏位置。因为,android:fitsSystemWindows属性是判断状态栏是否透明,如果透明就给整个layout加一个等于状态栏高度的padding属性,所以要想让状态栏与下方界面颜色相同,就只能通过设置背景色来解决。
android:background="@color/backgroundColor"
  • 至此,如果layout上什么都没有,此时,就已经完成了透明式状态栏,效果如下:


    空layout
  • 只是这样肯定不行,我们想要的是下面这样的:
希望结果

解决方法是:添加一个View在原来ActionBar的位置,又因为顶栏在多个界面中都会存在,所以我决定用include方法,然后在单独文件里,写顶栏:
tool_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                <!--设置id属性是为了在RelativeLayout布局中能够被定位 -->
                android:id="@+id/toolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:background="@color/backgroundColor"
                android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Application"
        android:textColor="@android:color/white"/>
</RelativeLayout>

layout.xml

   <include layout="@layout/tool_bar"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbarLayout"
        android:background="@android:color/white">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:layout_centerInParent="true"
            android:text="textView"/>
    </RelativeLayout>

然后,就是上图所显示的结果了。

  • P.S.

  1. 当然toolbar的背景颜色可以直接设置为透明@android:color/transparent,如果是浅色主题深色字体还好,如果是深色主题浅色字体,在编辑的时候,就会看不清楚文字,具体取舍,视情况而定。
  2. 有关于在浅色主题下,如何让状态栏深色显示,目前笔者还没找到适当方法,虽然网上都有android:windowLightStatusBar属性可以使用,但并没有效果,具体原因,笔者还在探索中。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容