一、自定义Toolbar的menu:
在menu下新建menu.xml文件,自定义menu的样式:
<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/action_search"
android:orderInCategory="80"
android:title="action_search"
app:showAsAction="ifRoom"
android:icon="@drawable/search_ic_selector"/>
</menu>
二、自定义Toolbar,Toolbar一般是共用:
新建common_toolbar.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/common_toolbar_top"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:navigationIcon="?attr/homeAsUpIndicator"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
</android.support.v7.widget.Toolbar>
注:其中app:navigationIcon="?attr/homeAsUpIndicator"用于设置返回图标
三、在布局文件中引入自定义的Toolbar:
<include
layout="@layout/common_toolbar">
</include>
四、activity中声明Toolbar以及对menu的事件监听:
注:Activity必须继承AppCompatActivity
1、声明Toolbar:
Toolbar toolbar = (Toolbar) findViewById(R.id.common_toolbar_top);
setSupportActionBar(toolbar);
2、Toolbar设置标题等:
setTitle(R.string.fragment_for_why_title);
3、对menu进行声明和事件监听:
menu声明:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
事件监听:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); //noinspection SimplifiableIfStatement
if (id == R.id.action_search) { return true;
} return super.onOptionsItemSelected(item);
}
五、最终效果图:
Demo下载地址:http://shouji.baidu.com/software/item?docid=8118536&from=as