继承LinearLayout,是一个垂直方向的LinearLayout,内部做了很多滚动事件的封装。
主要是为了解决CoordinatorLayout中控件覆盖的问题
必须是coordinatorLayout的子布局
例子
- 没有使用AppBarLayout
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:title="Hello Toolbar" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="16dp"
android:src="@drawable/icon_tab_publish"
app:elevation="8dp" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
可以看到toolbar和RecyclerView覆盖,这是因为coordinatorLayout本身就是一个FrameLayout,默认位置都是在左上角的
- 使用AppBarLayout
在toolbar上面添加AppBarLayout
在RecyclerView中设置layout_behavior=“com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior”
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:title="Hello Toolbar" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="16dp"
android:src="@drawable/icon_tab_publish"
app:elevation="8dp" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
layout_scrollFlags
当AppBarLayout接收到滚动事件时,它内部的子控件其实是可以指定如何去影响这些事件的,使用app:layout_scrollFlags,注意:是在子控件中指定这个属性的
- scroll
当RecyclerView向上滚动时,Toolbar跟着向上滚动并隐藏,recyclerview向下滚动时,当滚动到最上面,toolbar才会显示出来
- enterAlways
当RecyclerView向下滚动时,Toolbar跟着向下滚动并显示
- snap
当Toolbar还没完全显示或隐藏时,会根据当前滚动距离,自动选择隐藏或显示
- exitUntilCollapsed
需要配合collapsingToolbarLayout使用才有效果,当collapsingToolbarLayout随着滚动完成折叠后就保留在界面上, 不再移出屏幕