在这里推荐一篇文章:Android 详细分析AppBarLayout的五种ScrollFlags
上一篇文章将精美的水果图片展示出来了,但是有出来了一个新的问题:Toolbar被Recycleview挡住了,怎么解决呢?
原因分析:CoordinatorLayout控件是一个加强版的FrameLayout,FrameLayout中所有的控件在不进行明确定位的情况下都会默认摆在布局的左上角,从而产生了遮挡现象。
一般情况下,解决方案可能就是让Recycleview向下偏移一个Toolbar高度,从而保证不被遮挡。但是我们使用的是CoordinatorLayout!自然有更高明的办法。
使用AppBarLayout
这里我们使用Design Support中的另一个工具AppBarLayout,他是一个垂直方向的LinearLayout,内部做了很多滚动时间的封装。
只需两步解决Toolbar覆盖问题:
- 第一步,将Toolbar嵌套到AppBarLayout中
- 第二步,给RecycleView指定一个布局(app:layout_behavior)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_Layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<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" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycle_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/ic_done"
app:elevation="8dp" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:menu="@menu/nav_menu" />
</android.support.v4.widget.DrawerLayout>
运行,效果如图(我略微上滑了一下,用于区分这张图与接下来的一张图)
我们已经使用AppBarLayout解决了RecyclerView遮挡Toolbar的问题,但是AppBarLayout实现更多的Material Design 效果
仅需在Toolbar里添属性:app:layout_scrollFlags="scroll|enterAlways|snap"
(这里再提一下,这篇文章讲解了Android 详细分析AppBarLayout的五种ScrollFlags,讲的很好)
- scroll表示当RecycleView向上滚动的时候,Toolbar会跟着向上滑动并实现隐藏;
- enterAlways表示当RecycleView向下滑动并重新显示。
- snp表示Toolbar还没有完全隐藏或显示的时候,根据当前滚动的距离自动选择显示还是隐藏。
效果如图
(随着我们上滑RecycleView,Toolbar消失了,向下滑动RecycleView,Toolbar又会重新出现。)