实现类似Material Design 的状态栏
@(Blog)[马克飞象|Markdown|Android]
Android 4.4自带方法
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
<item name="android:windowTranslucentStatus" tools:targetApi="kitkat">true</item>
<item name="android:windowTranslucentNavigation" tools:targetApi="kitkat">true</item>
上面的代码和style实现的同一个功能,只需要使用一种即可。
如果只是使用了以上的代码,只是实现了一个全屏效果,我们还需要在布局文件中加入两个属性
<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"
android:fitsSystemWindows="true"
android:clipToPadding="true"
android:background="@color/status_bar_blue"
tools:context="com.example.focus.androidnote.statusbar.StatusBarActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/toolbar_blue"/>
</LinearLayout>
在网上找了很久,都没有发现可以单独设置StatusBar
颜色的方法,所以只能同通过设置布局文件的Root背景色来实现StatusBar
的颜色设置
使用SystemBarTint
由于使用系统自带API只能通过设置Background
来实现为StatusBar赋颜色,我们可以使用开源库SystemBarTint,来解决这个问题
- 代码
/* 激活主题 */
// 创建状态栏的管理实例
SystemBarTintManager tintManager = new SystemBarTintManager(this);
// 激活状态栏设置
tintManager.setStatusBarTintEnabled(true);
// 激活导航栏设置
tintManager.setNavigationBarTintEnabled(true);
/* 设置主题 */
// 设置一个状态栏资源
tintManager.setStatusBarTintColor(R.color.status_bar_blue);
- 布局
布局上和使用系统方法时一样,我们依然需要设置android:fitsSystemWindows
和android:clipToPadding
,但是要注意android:clipToPadding
不再是在Root上,而是要设置到Toolbar
上
<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"
android:clipToPadding="true"
android:background="@color/background_blue"
tools:context="com.example.focus.androidnote.statusbar.StatusBarActivity">
<android.support.v7.widget.Toolbar
android:fitsSystemWindows="true"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/toolbar_blue"/>
</LinearLayout>
参考
http://blog.csdn.net/spring_he/article/details/39701419
http://stackoverflow.com/questions/20781014/translucent-system-bars-and-content-margin-in-kitkat