我是怎么做到的:
mRecylerView.addOnScrollListener(new HideShowScrollListener() { @Override public void onHide() { //fab.animate().setInterpolator(new AccelerateDecelerateInterpolator()).scaleX(0).scaleY(0); // do your hiding animation here } @Override public void onShow() { // fab.animate().setInterpolator(new AccelerateDecelerateInterpolator()).scaleX(1).scaleY(1); // do your showing animation here } });
您将需要HideShowScrollListener.class
/** * This class is a ScrollListener for RecyclerView that allows to show/hide * views when list is scrolled. * */ public abstract class HideShowScrollListener extends RecyclerView.OnScrollListener { private static final int HIDE_THRESHOLD = 20; private int scrolledDistance = 0; private boolean controlsVisible = true; @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) { onHide(); controlsVisible = false; scrolledDistance = 0; } else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) { onShow(); controlsVisible = true; scrolledDistance = 0; } if((controlsVisible && dy>0) || (!controlsVisible && dy<0)) { scrolledDistance += dy; } } public abstract void onHide(); public abstract void onShow(); }
因为你正在使用CoordinatorLayout
你可以创建一个Behaviour
可以实现你所要求的自定义的自定义,如下例所示:
create
一个类extends CoordinatorLayout.Behavior
如下例所示:
public class QuickReturnFloaterBehavior extends CoordinatorLayout.Behavior{ private int distance; public QuickReturnFloaterBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) { return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0; } @Override public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) { if (dy > 0 && distance < 0 || dy < 0 && distance > 0) { child.animate().cancel(); distance = 0; } distance += dy; final int height = child.getHeight() > 0 ? (child.getHeight()) : 600/*update this accordingly*/; if (distance > height && child.isShown()) { hide(child); } else if (distance < 0 && !child.isShown()) { show(child); } } private void hide(View view) { view.setVisibility(View.GONE);// use animate.translateY(height); instead } private void show(View view) { view.setVisibility(View.VISIBLE);// use animate.translateY(-height); instead } }
现在要应用此behaviour
添加到您的布局
app:layout_behavior="com.example.QuickReturnFloaterBehavior"