默认的ToolBar可能是这个样子
有时候可能需要标题居中,可在布局中添加一个TextView
<android.support.v7.widget.Toolbar
android:id="@+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:titleTextColor="@android:color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:text="Center Title"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/white"
android:textStyle="bold"/>
</android.support.v7.widget.Toolbar>
然后去掉默认的Title
Toolbar toolbar = ((Toolbar) findViewById(R.id.toolBar));
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
然后界面应该是这个样子
二级页面看起来应该差一个返回按钮,这也很简单
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
返回按钮的颜色可能不是你想要的
在style 中新加一个style 如下
<style name="toolBar">
<item name="colorControlNormal">@android:color/white</item>
</style>
然后在ToolBar布局中添加属性
app:theme="@style/toolBar"
这个时候ToolBar应该长这个样子了
右边再来一个按钮
menu下新建一个menu文件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/ab_search"
android:icon="@drawable/menu_0"
android:title="action_search"
app:showAsAction="ifRoom"/>
</menu>
Activity中onCreateOptionsMenu
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.toolbar_main_menu, menu);
return true;
}
再加上事件监听
@Override
public boolean onOptionsItemSelected(MenuItem item) {
toast("onOptionsItemSelected");
return super.onOptionsItemSelected(item);
}