1.简单使用
*android:layout_height="?attr/actionBarSize" //设置为actionBar的高度
*android:background="?attr/colorPrimary" //设置背景色
*android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" //toolbar单独使用主题
*app:popupTheme="@style/ThemeOverlay.AppCompat.Light" //弹窗主题
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</FrameLayout>
//传入toolbar使外观与功能与ActionBar的功能一致。
setSupportActionBar(toolbar);
2.添加按钮
*app:showAsAction="" //按钮显示位置 always表示永远显示在Toolbar中,如果屏幕控件不够则不显示;ifRoom表示
屏幕空间足够的情况下显示在Toolbar中,不够的话就显示在菜单栏中;never表示永远显示在菜单栏中。注:Toolbar
中的action按钮只会显示图片,菜单栏中的action按钮只会显示文字。
2.1.新建布局
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/backup"
android:icon="@mipmap/ic_launcher"
android:title="BackUp"
app:showAsAction="always"/>
<item
android:id="@+id/delete"
android:icon="@mipmap/ic_launcher"
android:title="Delete"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/settings"
android:icon="@mipmap/ic_launcher"
android:title="Settings"
app:showAsAction="never"/>
</menu>
2.2加载布局并添加点击事件
//加载布局
@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.backup:
Toast.makeText(this,"You clicked Backup",Toast.LENGTH_SHORT).show();
break;
case R.id.delete:
Toast.makeText(this,"You clicked Delete",Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(this,"You clicked Settings",Toast.LENGTH_SHORT).show();
break;
}
return true;
}