<TextView
android:layout_width=“match_parent”
android:layout_height=“64dp”
android:layout_gravity=“bottom”
android:text=“Top”
android:textSize=“32sp”
android:textColor="@color/white"
android:gravity=“center”
android:textStyle=“bold”/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
将 AppBarLayout
中需要上滑隐藏的部分的 scrollFlag
指定为 scroll
,在RecyclerView 中指定 behavior
为 appbar_scrolling_view_behavior
就可以实现最简单的吸顶嵌套滑动,如下:
看起来像带有 header 的 RecyclerView 在滑动,但其实是嵌套滑动。
layout_scrollFlags
和 layout_behavior
有很多可选值,配合起来可以实现多种效果,不只限于嵌套滑动。具体可以参考 API 文档。
使用 CoordinatorLayout
实现嵌套滑动比手动实现要好得多,既可以实现连贯的吸顶嵌套滑动,又支持 fling。而且是官方提供的布局,可以放心使用,出 bug 的几率很小,性能也不会有问题。不过也正是因为官方将其封装得很好,使用 CoordinatorLayout
很难实现比较复杂的嵌套滑动布局,比如多级嵌套滑动。
3、嵌套滑动组件 NestedScrollingParent 和 NestedScrollingChild
NestedScrollingParent
和 NestedScrollingChild
是 google 官方提供地一套专门用来解决嵌套滑动地组件。它们是两个接口,代码如下:
public interface NestedScrollingParent2 extends NestedScrollingParent {
boolean onStartNestedScroll(@NonNull View child, @NonNull View target, @ScrollAxis int axes,
@NestedScrollType int type);
void onNestedScrollAccepted(@NonNull View child, @NonNull View target, @ScrollAxis int axes,
@NestedScrollType int type);
void onStopNestedScroll(@NonNull View target, @NestedScrollType int type);
void onNestedScroll(@NonNull View target, int dxConsumed, int dyConsumed,
int dxUnconsumed, int dyUnconsumed, @NestedScrollType int type);
void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed,
@NestedScrollType int type);
}
public interface NestedScrollingChild2 extends NestedScrollingChild {
boolean startNestedScroll(@ScrollAxis int axes, @NestedScrollType int type);
void stopNestedScroll(@NestedScrollType int type);
boolean hasNestedScrollingParent(@NestedScrollType int type);
boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
int dxUnconsumed, int dyUnconsumed, @Nullable int[] offsetInWindow,
@NestedScrollType int type);
boolean dispatchNestedPreScroll(int dx, int dy, @Nullable int[] consumed,
@Nullable in