一直很喜欢QQ的TopBar延伸至状态栏的感觉,网上关于这个叫沉浸式状态栏还是半透明状态栏有很多争议,我也不管这么多了,只要好看就行了,所以就叫沉浸式状态栏吧。自己写了一个,效果如下:
-
5.0模拟器的效果
-
4.4模拟器的效果
首先只有Android4.4及其以上的版本才支持这个沉浸式状态栏,其次我们可以发现5.0版本并非一个渐进的效果,而是一个更深一点的颜色,有的大神为了更符合MD的规范,对4.4做了适配,我这里偷个懒,就不做适配工作了。
好,废话不多说,现在就开始一步一步实现沉浸式状态栏的效果。
1.因为android:windowTranslucentStatus这个属性是Android4.4及其以上版本才有的,在res目录下新建values-19文件夹,并自定义一个style
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="@style/BaseAppTheme">
<item name="android:windowTranslucentStatus">true</item>
</style>
</resources>
2.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MainActivity"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/toolbar_padding_top"
android:background="@color/top_bar_color"> //这里设置TopBar的背景色
<com.houxy.wechat.view.CircleImageView //这里是自定义的一个控件,就是上面的圆形头像
android:layout_width="35dp"
android:layout_height="35dp"
android:src="@mipmap/default_head"
android:textColor="@color/base_color_text_white"
android:layout_centerInParent="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="@dimen/margin_15"/>
</android.support.v7.widget.Toolbar>
</LinearLayout>
这里我们需要特别注意android:paddingTop这个属性,我们来看看如果不加会怎么样!
-
4.4模拟器的效果
-
5.0模拟器的效果
Paste_Image.png
明显可以看到TopBar和状态栏像是挤到一起去了。我最开始的解决方案是给toolbar加上
android:fitsSystemWindows="true"
这个属性。
没错,一般情况下这样就能解决这个bug,但是如果我们给这个活动添加一个搜索框,我们就会发现
![](https://img.haomeiwen.com/i1715286/61bf46249902e290.png)
出现了这个bug,我想应该是输入法的弹出,导致view的变化吧,所以添加
android:fitsSystemWindows="true"
这个属性是有风险的.最后我的解决方案是给topbar添加一个paddingTop,而不是添加android:fitsSystemWindows="true"
这个属性。为了适配,我们在valeus/dimens.xml的文件下定义
<dimen name="toolbar_padding_top">0dp</dimen>
在values-v19/dimens.xml的文件下定义
<dimen name="toolbar_padding_top">25dp</dimen>
至于为什么这toolbar_padding_top=25dp,这个是因为我们的状态栏的高度为这么多。加上这个padding_top就把我们的toolbar从状态栏上挤下来了。
-
加上paddingTop后的效果
再也不用担心输入法的弹出对view造成的影响,而且4.4以下的版本也能很好的适配
![](https://img.haomeiwen.com/i1715286/c5617f59df6dd800.png?
imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
3.最后在活动里setSupportActionBar就大功告成了
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....//省略
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);//不要标题
}
最近我又发现一个bug,就是在使用沉浸式状态栏的时候,如果底部有editText,点击它,弹出的输入法会将editText遮住。
![](https://img.haomeiwen.com/i1715286/5d3cf104527a7904.png)
解决方法是在被遮挡住的编辑框所在的根布局添加属性
android:fitsSystemWindows="true"
![](https://img.haomeiwen.com/i1715286/0189897b734958e4.png)
参考:Android 沉浸式状态栏攻略 让你的状态栏变色吧
网友评论