android:CoordinatorLayout+AppBarLayout实现停靠吸顶
一,代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">
<com.google.android.material.appbar.AppBarLayout
app:elevation="0dp"
android:background="#00000000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:textColor="@color/white"
android:background="#2BDC70"
android:gravity="center"
android:textSize="32sp"
android:text="滚动后会隐藏"
app:layout_scrollFlags="scroll|snap"/>
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:textColor="@color/white"
android:background="#FD2E54"
android:gravity="center"
android:textSize="32sp"
android:text="固定头部"
/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:text="其他内容"
android:gravity="center_horizontal"
android:textColor="@color/white"
android:textSize="38sp"
android:layout_height="800dp"
android:background="#4A8A9E"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
说明:
scroll | snap
snap简单理解,就是Child View滚动比例的一个吸附效果。
也就是说,Child View不会存在局部显示,之滚动Child View的部分的情况;
当我们松开手指时,Child View要么向上全部滚出屏幕,要么向下全部滚进屏幕,要么完全显示,要么完全隐藏;
使用它可以确保childView不会滑动停止在中间的状态.
scroll:
伴随着scrollingView的滚动事件而滚出或滚进屏幕,
当ScrollView将要向下滚动的时候,优先滚动的是自己,
当自己滚动到顶部头的时候,再开始触发滚动AppBarLayoout中的childView;
当ScrollView将要向上滚动的时候,
优先将AppBarLayout的childView滚出屏幕,
然后ScrollView才开始滚动;
即:childview象scrollview在顶部的一部分一样
ScrollFlags的其他取值还包括:
scroll | enterAlways
scroll | enterAlways | enterAlwaysCollapsed
scroll | exitUntilCollapsed
可参考:
https://blog.csdn.net/eyishion/article/details/80282204
二,测试效果:

浙公网安备 33010602011771号