实际上,实现起来相当容易。
第一步——改变Toolbar的高度:
所以对我来说它看起来像这样:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
然后你覆盖v19的资源:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Style properties -->
....
<!-- These properties are important:-->
<item name="android:windowTranslucentStatus">true</item>
<item name="windowActionBarOverlay">false</item>
<item name="android:windowActionBarOverlay">false</item>
<item name="android:fitsSystemWindows">false</item>
</style>
</resources>
然后,在Activity 中,将padding 设置为Toolbar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
......
......
public int getStatusBarHeight() {
int result = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
}
return result;
}
实际上,差不多就是这样。现在,一旦我想更改工具栏的颜色,我将调用它:
if (getSupportActionBar() != null) {
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.GREEN));
}
活动的布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="false"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
注意!在 Kitkat 操作系统之前的版本中,状态栏保持不变,不透明。
我已将测试应用程序的源代码上传到我的保管箱 - feel free to check it out。
希望对你有帮助