简介
Toolbar是在 Android 5.0 开始推出的一个 Material Design 风格的导航控件 ,Google 非常推荐大家使用 Toolbar 来作为Android客户端的导航栏,以此来取代之前的 Actionbar 。与 Actionbar 相比, Toolbar 明显要灵活的多。它不像 Actionbar 一样,一定要固定在Activity的顶部,而是可以放到界面的任意位置。
使用步骤
1.App Theme
设置为<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
2.布局中声明
<android.support.v7.widget.Toolbar
android:background="@color/colorPrimary"
android:id="@+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
3.代码中设定
Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
3.1 设置标题
注意:需要在setSupportActionBar(toolbar);之前设置标题,否则无效。
toolbar.setTitle("标题");
3.2 其他设置
toolbar.setSubtitle("子标题");
// 导航栏图标
toolbar.setNavigationIcon(R.mipmap.a28);
// 设置App Logo
toolbar.setLogo(R.mipmap.ic_launcher);
<!-- 设置自定义控件 -->
<android.support.v7.widget.Toolbar
android:id="@+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定义控件"/>
// 设置Menu,需要重写onCreateOptionsMenu()方法
toolbar.inflateMenu(R.menu.menu);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}