Toolbar
Toolbar替换Actionbar
Actionbar被限定使用在活动的顶部,没有办法实现更多的效果,于是用Toolbar替换掉Actionbar
Actionbar的位置
修改成
替换Actionbar
在xml中添加Toolbar控件。
在Material Design出现以后,为了兼容以前的版本,这里要新开一个命名空间app 之后就可以像android空间那样使用app里的属性了。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
>
<androidx.appcompat.widget.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"/>
</LinearLayout>
在Activity中将toolbar添加进去
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar的常用功能
为了让Toolbar的功能更丰富一些,可以在menu文件夹下添加一个toolbar.xml,然后通过onCreateOptionsMenu的方法加载进来就好。
toolbar.xml
<?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">
<item
android:id="@+id/backup"
android:icon="@drawable/back_bg"
android:title="Backup"
app:showAsAction="always"/>
<item
android:id="@+id/delete"
android:icon="@drawable/ic_delete"
android:title="Delete"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/setting"
android:icon="@drawable/ic_settings"
android:title="Setting"
app:showAsAction="never"/>
</menu>
其中Toolbar中只会显示图标,而菜单中只会显示文字。
引入toolbar.xml
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.backup:
Toast.makeText(this,"You click the back",Toast.LENGTH_SHORT).show();
break;
case R.id.delete:
Toast.makeText(this,"You Click the delete",Toast.LENGTH_SHORT).show();
break;
case R.id.setting:
Toast.makeText(this,"You click the setting",Toast.LENGTH_SHORT).show();
break;
default:
}
return true;
}