Actionbar一直使用的不是很好,刷知乎看见说actionbar已经过时了,现在Google推荐使用Toolbar,正好就来学学吧。
(1)ToolBar的引入
1)隐藏原本的ActionBar
隐藏可以通过修改我们继承的主题为:Theme.AppCompat.Light.NoActionBar,当然也可以通过设置以下属性完成:
<item name="windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
我们这里选择前者:
修改res/values/styles.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
2)在布局文件中声明
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="@color/colorPrimaryDark"/>
3)代码中设定
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// App Logo
toolbar.setLogo(R.mipmap.ic_launcher);
// Title
toolbar.setTitle("App Title");
// Sub Title
toolbar.setSubtitle("Sub title");
}
}
一个初步的Toolbar就是这样的,要自己定义style.
颜色的属性说明,还是下面这张图最清楚了: