Toolbar
由于ActionBar难以定制,很大程度上限制了开发人员,比如标题文字大小、间距等不易实现个性化,所以又引入了Toolbar的使用,与 Actionbar 相比, Toolbar 明显要灵活的多。它不像 Actionbar 一样,一定要固定在Activity的最上面,而是可以放到界面的任意位置。
Toolbar 是在 Android 5.0 才开始加上的,安卓 为了将这一设计兼容,自然也少不了要推出兼容版的 Toolbar 。为此,我们需要在工程中引入 appcompat-v7 的兼容包,使用 android.support.v7.widget.Toolbar 进行开发。(引入大神的讲解)。
接下来我们讲解如何使用Toolbar,废话不多说直接上案例。
首先我们需要创建安卓项目,在这里我就不讲解如何创建安卓项目了。
在xml中编写如下代码:
<androidx.constraintlayout.widget.ConstraintLayout 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:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:background="@color/colorPrimary"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="你好" />
</androidx.appcompat.widget.Toolbar>
</androidx.constraintlayout.widget.ConstraintLayout>
在java中编写如下代码:
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//隐藏掉系统原先的导航栏
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
Toolbar toolbar= (Toolbar)findViewById(R.id.toolbar);
//设置导航栏图标
toolbar.setNavigationIcon(R.drawable.se);
//设置app logo
toolbar.setLogo(R.mipmap.ic_launcher);
//设置主标题
toolbar.setTitle("主题");
//设置子标题
toolbar.setSubtitle("子题");
//toolbar.setSubtitleTextColor(Integer.parseInt("#C71585"));
//设置右上角的填充菜单 说白了就是添加一个选项菜单
toolbar.inflateMenu(R.menu.base_toolbar_menue);
}
}
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
表示隐藏掉系统原先的导航栏(注意,我的MainActivity是继承了AppCompatActivity的, 如果是继承Activity就应该调用requestWindowFeature(Window.FEATURE_NO_TITLE));
最重要的一点是隐藏掉系统原先的导航栏必须在setContentView(R.layout.activity_main);的上面如果不在它的上面就是之前为什么直接闪退的原因这是十分重要的必须记住。
在menu中编写如下代码:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/item1"
android:icon="@mipmap/two"
android:title="item"
app:showAsAction="ifRoom" />
<item
android:id="@+id/item3"
android:title="搜索"
app:showAsAction="never" />
<item
android:id="@+id/item4"
android:title="查找"
app:showAsAction="never" />
</menu>
我们使用Toolbar创建的一个简单案例以完成。
看最终效果图:
路漫漫其修远兮,吾将上下而求索。