网上给出的方法大致为一下四种,择优食用
1. 自定义一个 behavior
public class FlingBehavior extends AppBarLayout.Behavior {
private static final int TOP_CHILD_FLING_THRESHOLD = 3;
private boolean isPositive;
public FlingBehavior() {
}
public FlingBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) {
if (velocityY > 0 && !isPositive || velocityY < 0 && isPositive) {
velocityY = velocityY * -1;
}
if (target instanceof RecyclerView && velocityY < 0) {
final RecyclerView recyclerView = (RecyclerView) target;
final View firstChild = recyclerView.getChildAt(0);
final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild);
consumed = childAdapterPosition > TOP_CHILD_FLING_THRESHOLD;
}
return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
}
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
isPositive = dy > 0;
}
}
2. 监听 RecyclerView 滑动,设置 AppBarLayout 在列表第一个直接展开
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
int visiblePosition = linearLayoutManager.findFirstCompletelyVisibleItemPosition() ;
if (visiblePosition == 0 && appBarLayout != null) {
appBarLayout.setExpanded(true, true) ;
}
}
}
3. 使用第三方库
compile "me.henrytao:smooth-app-bar-layout:<latest-support-design-version>.<latest-smooth-app-bar-layout-fix>"
4. 升级到 support:26.0.0 及以上
谷歌说在 support 26 以上已经解决了改问题,但是我这里没去测试,就不好下结论了,可以尝试。
compile 'com.android.support:design:26.0.0'
缺点分析
方法1:在滑动列表时偶尔会出现 AppBarLayout 全部展开后,列表数据从 AppBarLayout 中拉出。
方法2:当滑动到顶部会直接展开 AppBarLayout ,效果有点突兀(目前项目上用的就是这个...)改为升级 support:design:26.1.0
方法3:当下方是一个 ViewPager 时貌似不支持(大概是因为我菜吧 ,效果没实现出来)
方法4:没去测试,因为手头项目用的是 25.3.1 的 support 包,暂时不想替换,万一出现什么幺蛾子还得填坑!
2018-5-17 更新
最终解决办法还是升级到compile 'com.android.support:design:26.1.0'
升级过程可能出现 Error:Failed to resolve: com.android.support:support-v4:26.1.0)
的问题,解决办法是:参考 stackoverflow 上的高票答案
还有可能出现 Error:SSL peer shut down incorrectly报错
, 解决办法是
1. 参考 stackoverflow 上的高票答案
2. clean project ( 笔者采用这个方法成功 )
参考
Flinging with RecyclerView + AppBarLayout
smooth-app-bar-layout