先将app的theme改变为noActionBar
XML布局
xml version=
"1.0"
encoding=
"utf-8"
?>
<
FrameLayout
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"
android
:layout_width=
"match_parent"
android
:layout_height=
"match_parent"
>
<
android.support.v7.widget.Toolbar
android
:id=
"@+id/myTool"
android
:layout_width=
"match_parent"
android
:layout_height=
"?attr/actionBarSize"
android
:background=
"#99ffcc"
android
:theme=
"@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app
:popupTheme=
"@style/ThemeOverlay.AppCompat.Light"
>
android.support.v7.widget.Toolbar
>
FrameLayout
>
RES资源
在res文件夹中创建menu文件夹 , 右键创建menu资源文件
<
item
android
:id=
"@+id/menu1"
android
:icon=
"@drawable/ic_archive_black_48dp" 图标
android
:title=
"menu1" 标题
app
:showAsAction=
"always"
>
item
> 显示的位置
always 总是显示
ifRoom 屏幕空间不足时就会隐藏
never 从不显示
JAVA
通过
setSupportActionBar();设置
加载menu资源文件
@Override
public boolean
onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.
toolbar
, menu);
return true
;
}
设置监听
@Override
public boolean
onOptionsItemSelected(MenuItem item) {
switch
(item.getItemId()) {
case
R.id.
menu1
:
Toast.
makeText
(
this
,
"menu1"
, Toast.
LENGTH_SHORT
).show();
break
;
case
R.id.
menu2
:
Toast.
makeText
(
this
,
"menu2"
, Toast.
LENGTH_SHORT
).show();
break
;
case
R.id.
menu3
:
Toast.
makeText
(
this
,
"menu3"
, Toast.
LENGTH_SHORT
).show();
break
;
}
return true
;
}
actionBar
= getSupportActionBar();
if
(
actionBar
!=
null
){
actionBar
.setDisplayHomeAsUpEnabled(
true
); //默认为小箭头 id为
android.R.id.
home
actionBar
.setHomeAsUpIndicator(R.drawable.
ic_visibility_black_48dp
);
}