虽说现在的标题栏是使用Toolbar来编写的,不过它看上去和传统的ActionBar没什么两样,只不过可以响应RecyclerView的滚动事件来进行隐藏和显示。还可以根据自己的喜好随意定制标题栏的样式
这里实现一个可折叠式标题栏的效果,要借助CollapsingToolbarLayout这个工具
可折叠式标题栏:CollapsingToolbarLayout
顾名思义,CollapsingToolbarLayout是一个作用于Toolbar基础之上的布局,它也是由Material库提供的
CollapsingToolbarLayout可以让Toolbar的效果变得更加丰富,不仅仅是展示一个标题栏,而且能够实现非常华丽的效果
不过,CollapsingToolbarLayout是不能独立存在的,它在设计的时候就被限定只能作为AppBarLayout的直接子布局来使用。而AppBarLayout又必须是CoordinatorLayout的子布局,因此要实现的功能其实需要综合运用前面所了解的各种知识
首先我们需要一个额外的Activity作为水果的详情展示界面,右击com.example.materialtest包→New→Activity→Empty Activity,创建一个FruitActivity,并将布局名指定成activity_fruit.xml
然后开始编写水果详情展示界面的布局。由于整个布局文件比较复杂,这里准备采用分段编写的方式
activity_fruit.xml中的内容主要分为两部分,一个是水果标题栏,一个是水果内容详情
首先实现标题栏部分,这里使用CoordinatorLayout作为最外层布局
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
</androidx.coordinatorlayout.widget.CoordinatorLayout>
这里就注意要始终记得定义一个xmlns:app的命名空间,在Material Design的开发中会经常用到它
接着在CoordinatorLayout中嵌套一个AppBarLayout
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appBar"
android:layout_width="match_parent"
android:layout_height="250dp">
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
这里给AppBarLayout定义了一个id,将它的宽度指定为match_parent,高度指定为250 dp
接下来在AppBarLayout中再嵌套一个CollapsingToolbarLayout
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appBar"
android:layout_width="match_parent"
android:layout_height="250dp">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="@+id/collapsingToolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:contentScrim="@color/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
</com.google.android.material.appbar.CollapsingToolbarLayout>
</