好久没有写Android控件了,正好最近项目有个自定义控件的需求,整理了下作个总结,主要是实现相似于抖音翻页的效果,可是有有点不一样,须要在底部漏出后面的view,这样说可能很差理解,看下Demo,按页滑动,后面的View有放大缩放的动画,滑动速度太小时会有回到原位的效果,下滑也是按页滑动的效果。android
有的小伙伴可能说这个用 SnapHelper
就能够了,没错,翻页是要结合这个,可是也不是纯粹靠这个,由于底部须要漏出来后面的view,因此LayoutManager
就不能简单的使用LinearLayoutManager
,须要去自定义LayoutManager
,而后再自定义SnapHelper
。缓存
若是把自定义LayoutManager
和SnapHelper
放在一篇里面会太长,因此咱们今天主要分析SnapHelper
。bash
本文分析的源码是基于recyclerview-v7-26.1.0
app
Scroll
和Fling
这方面参考个人上篇分享:RecyclerView之Scroll和Flingide
总结一下调用栈就是:源码分析
SnapHelper
onFling ---> snapFromFling
复制代码
上面获得最终位置targetPosition
,把位置给RecyclerView.SmoothScroller
, 而后就开始滑动了:post
RecyclerView.SmoothScroller
start --> onAnimation
复制代码
在滑动过程当中若是targetPosition
对应的targetView
已经layout出来了,就会回调SnapHelper
,而后计算获得到当前位置到targetView
的距离dx,dy
动画
SnapHelper
onTargetFound ---> calculateDistanceToFinalSnap
复制代码
而后把距离dx,dy
更新给RecyclerView.Action
:ui
RecyclerView.Action
update --> runIfNecessary --> recyclerView.mViewFlinger.smoothScrollBy
复制代码
最后调用RecyclerView.ViewFlinger
, 而后又回到onAnimation
this
class ViewFlinger implements Runnable
public void smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) {
if (mInterpolator != interpolator) {
mInterpolator = interpolator;
mScroller = new OverScroller(getContext(), interpolator);
}
setScrollState(SCROLL_STATE_SETTLING);
mLastFlingX = mLastFlingY = 0;
mScroller.startScroll(0, 0, dx, dy, duration);
postOnAnimation();
}
复制代码
SnapHelper
源码分析上面其实已经接触到部分的SnapHelper
源码, SnapHelper
实际上是一个抽象类,有三个抽象方法:
/**
* Override to provide a particular adapter target position for snapping.
*
* @param layoutManager the {@link RecyclerView.LayoutManager} associated with the attached
* {@link RecyclerView}
* @param velocityX fling velocity on the horizontal axis
* @param velocityY fling velocity on the vertical axis
*
* @return the target adapter position to you want to snap or {@link RecyclerView#NO_POSITION}
* if no snapping should happen
*/
public abstract int findTargetSnapPosition(LayoutManager layoutManager, int velocityX,
int velocityY);
/**
* Override this method to snap to a particular point within the target view or the container
* view on any axis.
* <p>
* This method is called when the {@link SnapHelper} has intercepted a fling and it needs
* to know the exact distance required to scroll by in order to snap to the target view.
*
* @param layoutManager the {@link RecyclerView.LayoutManager} associated with the attached
* {@link RecyclerView}
* @param targetView the target view that is chosen as the view to snap
*
* @return the output coordinates the put the result into. out[0] is the distance
* on horizontal axis and out[1] is the distance on vertical axis.
*/
@SuppressWarnings("WeakerAccess")
@Nullable
public abstract int[] calculateDistanceToFinalSnap(@NonNull LayoutManager layoutManager,
@NonNull View targetView);
/**
* Override this method to provide a particular target view for snapping.
* <p>
* This method is called when the {@link SnapHelper} is ready to start snapping and requires
* a target view to snap to. It will be explicitly called when the scroll state becomes idle
* after a scroll. It will also be called when the {@link SnapHelper} is preparing to snap
* after a fling and requires a reference view from the current set of child views.
* <p>
* If this method returns {@code null}, SnapHelper will not snap to any view.
*
* @param layoutManager the {@link RecyclerView.LayoutManager} associated with the attached
* {@link RecyclerView}
*
* @return the target view to which to snap on fling or end of scroll
*/
@SuppressWarnings("WeakerAccess")
@Nullable
public abstract View findSnapView(LayoutManager layoutManager);
复制代码
上面三个方法就是咱们重写SnapHelper
须要实现的,很重要,简单介绍下它们的做用和调用时机:
findTargetSnapPosition
用来找到最终的目标位置,在fling操做刚触发的时候会根据速度计算一个最终目标位置,而后开始fling操做calculateDistanceToFinalSnap
这个用来计算滑动到最终位置还须要滑动的距离,在一开始attachToRecyclerView
或者targetView layout的时候会调用findSnapView
用来找到上面的targetView,就是须要对其的view,在calculateDistanceToFinalSnap
调用以前会调用该方法。
咱们看下SnapHelper
怎么用的,其实就一行代码:
this.snapHelper.attachToRecyclerView(view);
复制代码
SnapHelper
正是经过该方法附着到RecyclerView上,从而实现辅助RecyclerView滚动对齐操做,那咱们就从上面的attachToRecyclerView
开始入手:
public void attachToRecyclerView(@Nullable RecyclerView recyclerView)
throws IllegalStateException {
if (mRecyclerView == recyclerView) {
return; // nothing to do
}
if (mRecyclerView != null) {
destroyCallbacks();
}
mRecyclerView = recyclerView;
if (mRecyclerView != null) {
setupCallbacks();
mGravityScroller = new Scroller(mRecyclerView.getContext(),
new DecelerateInterpolator());
snapToTargetExistingView();
}
}
复制代码
在attachToRecyclerView()
方法中会清掉SnapHelper
以前保存的RecyclerView
对象的回调(若是有的话),对新设置进来的RecyclerView
对象设置回调,而后初始化一个Scroller
对象,最后调用snapToTargetExistingView()
方法对SnapView进行对齐调整。
该方法的做用是对SnapView进行滚动调整,以使得SnapView达到对齐效果。
看下源码:
void snapToTargetExistingView() {
if (mRecyclerView == null) {
return;
}
LayoutManager layoutManager = mRecyclerView.getLayoutManager();
if (layoutManager == null) {
return;
}
View snapView = findSnapView(layoutManager);
if (snapView == null) {
return;
}
int[] snapDistance = calculateDistanceToFinalSnap(layoutManager, snapView);
if (snapDistance[0] != 0 || snapDistance[1] != 0) {
mRecyclerView.smoothScrollBy(snapDistance[0], snapDistance[1]);
}
}
复制代码
snapToTargetExistingView()
方法就是先找到SnapView
,而后计算SnapView
当前坐标到目的坐标之间的距离,而后调用RecyclerView.smoothScrollBy()
方法实现对RecyclerView
内容的平滑滚动,从而将SnapView
移到目标位置,达到对齐效果。
其实这个时候RecyclerView
还没进行layout,通常findSnapView
会返回null,不须要对齐。
SnapHelper
要有对齐功能,确定须要知道RecyclerView
的滚动scroll和fling过程的,这个就是经过回调接口实现。再看下attachToRecyclerView
的源码:
public void attachToRecyclerView(@Nullable RecyclerView recyclerView)
throws IllegalStateException {
if (mRecyclerView == recyclerView) {
return; // nothing to do
}
if (mRecyclerView != null) {
destroyCallbacks();
}
mRecyclerView = recyclerView;
if (mRecyclerView != null) {
setupCallbacks();
mGravityScroller = new Scroller(mRecyclerView.getContext(),
new DecelerateInterpolator());
snapToTargetExistingView();
}
}
复制代码
一开始会先清空以前的回调接口而后再注册接口,先看下destroyCallbacks
:
/**
* Called when the instance of a {@link RecyclerView} is detached.
*/
private void destroyCallbacks() {
mRecyclerView.removeOnScrollListener(mScrollListener);
mRecyclerView.setOnFlingListener(null);
}
复制代码
能够看出SnapHelper
对RecyclerView
设置了两个回调,一个是OnScrollListener
对象mScrollListener
,另一个就是OnFlingListener
对象。
再看下setupCallbacks
:
/**
* Called when an instance of a {@link RecyclerView} is attached.
*/
private void setupCallbacks() throws IllegalStateException {
if (mRecyclerView.getOnFlingListener() != null) {
throw new IllegalStateException("An instance of OnFlingListener already set.");
}
mRecyclerView.addOnScrollListener(mScrollListener);
mRecyclerView.setOnFlingListener(this);
}
复制代码
SnapHelper
实现了RecyclerView.OnFlingListener
接口,因此OnFlingListener
就是SnapHelper
自身。
先来看下RecyclerView.OnScrollListener
对象mScrollListener
先看下mScrollListener
是怎么实现的:
private final RecyclerView.OnScrollListener mScrollListener =
new RecyclerView.OnScrollListener() {
boolean mScrolled = false;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE && mScrolled) {
mScrolled = false;
snapToTargetExistingView();
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dx != 0 || dy != 0) {
mScrolled = true;
}
}
};
复制代码
mScrolled = true
表示以前滚动过,RecyclerView.SCROLL_STATE_IDLE
表示滚动中止,这个不清楚的能够看考以前的博客RecyclerView之Scroll和Fling。这个监听器的实现其实很简单,就是在滚动中止的时候调用snapToTargetExistingView
对目标View进行滚动调整对齐。
RecyclerView.OnFlingListener
接口只有一个方法,这个就是在Fling
操做触发的时候会回调,返回true就是已处理,返回false就会交给系统处理。
/**
* This class defines the behavior of fling if the developer wishes to handle it.
* <p>
* Subclasses of {@link OnFlingListener} can be used to implement custom fling behavior.
*
* @see #setOnFlingListener(OnFlingListener)
*/
public abstract static class OnFlingListener {
/**
* Override this to handle a fling given the velocities in both x and y directions.
* Note that this method will only be called if the associated {@link LayoutManager}
* supports scrolling and the fling is not handled by nested scrolls first.
*
* @param velocityX the fling velocity on the X axis
* @param velocityY the fling velocity on the Y axis
*
* @return true if the fling was handled, false otherwise.
*/
public abstract boolean onFling(int velocityX, int velocityY);
}
复制代码
看下SnapHelper
怎么实现onFling()
方法:
@Override
public boolean onFling(int velocityX, int velocityY) {
LayoutManager layoutManager = mRecyclerView.getLayoutManager();
if (layoutManager == null) {
return false;
}
RecyclerView.Adapter adapter = mRecyclerView.getAdapter();
if (adapter == null) {
return false;
}
int minFlingVelocity = mRecyclerView.getMinFlingVelocity();
return (Math.abs(velocityY) > minFlingVelocity || Math.abs(velocityX) > minFlingVelocity)
&& snapFromFling(layoutManager, velocityX, velocityY);
}
复制代码
首先会获取mRecyclerView.getMinFlingVelocity()
须要进行fling操做的最小速率,只有超过该速率,Item才能在手指离开的时候进行Fling
操做。 关键就是调用snapFromFling
方法实现平滑滚动。
看下怎么实现的:
private boolean snapFromFling(@NonNull LayoutManager layoutManager, int velocityX,
int velocityY) {
if (!(layoutManager instanceof ScrollVectorProvider)) {
return false;
}
SmoothScroller smoothScroller = createScroller(layoutManager);
if (smoothScroller == null) {
return false;
}
int targetPosition = findTargetSnapPosition(layoutManager, velocityX, velocityY);
if (targetPosition == RecyclerView.NO_POSITION) {
return false;
}
smoothScroller.setTargetPosition(targetPosition);
layoutManager.startSmoothScroll(smoothScroller);
return true;
}
复制代码
- 首先判断是否是实现了
ScrollVectorProvider
接口,系统提供的Layoutmanager默认都实现了该接口- 建立SmoothScroller对象,默认是
LinearSmoothScroller
对象,会用LinearInterpolator
进行平滑滚动,在目标位置成为Recyclerview
的子View时会用DecelerateInterpolator
进行减速中止。- 经过
findTargetSnapPosition()
方法,以layoutManager和速率做为参数,找到targetSnapPosition,这个方法就是自定义SnapHelper
须要实现的。- 把targetSnapPosition设置给平滑滚动器,而后开始进行滚动操做。
很明显重点就是要看下平滑滚动器了。
看下系统怎么实现:
@Nullable
protected LinearSmoothScroller createSnapScroller(LayoutManager layoutManager) {
if (!(layoutManager instanceof ScrollVectorProvider)) {
return null;
}
return new LinearSmoothScroller(mRecyclerView.getContext()) {
@Override
protected void onTargetFound(View targetView, RecyclerView.State state, Action action) {
int[] snapDistances = calculateDistanceToFinalSnap(mRecyclerView.getLayoutManager(),
targetView);
final int dx = snapDistances[0];
final int dy = snapDistances[1];
final int time = calculateTimeForDeceleration(Math.max(Math.abs(dx), Math.abs(dy)));
if (time > 0) {
action.update(dx, dy, time, mDecelerateInterpolator);
}
}
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
}
};
}
复制代码
在经过findTargetSnapPosition()
方法找到的targetSnapPosition成为Recyclerview
的子View时(根据Recyclerview
的缓存机制,这个时候可能该View在屏幕上还看不到),会回调onTargetFound
,看下系统定义:
/**
* Called when the target position is laid out. This is the last callback SmoothScroller
* will receive and it should update the provided {@link Action} to define the scroll
* details towards the target view.
* @param targetView The view element which render the target position.
* @param state Transient state of RecyclerView
* @param action Action instance that you should update to define final scroll action
* towards the targetView
*/
protected abstract void onTargetFound(View targetView, State state, Action action);
复制代码
传入的第一个参数targetView
就是咱们但愿滚动到的位置对应的View,最后一个参数就是咱们能够用来通知滚动器要减速滚动的距离。
其实就是咱们要在这个方法里面告诉滚动器在目标子View layout出来后还须要滚动多少距离, 而后经过Action
通知滚动器。
第二个方法是计算滚动速率,返回值会影响onTargetFound
中的calculateTimeForDeceleration
方法,看下源码:
private final float MILLISECONDS_PER_PX;
public LinearSmoothScroller(Context context) {
MILLISECONDS_PER_PX = calculateSpeedPerPixel(context.getResources().getDisplayMetrics());
}
/**
* Calculates the time it should take to scroll the given distance (in pixels)
*
* @param dx Distance in pixels that we want to scroll
* @return Time in milliseconds
* @see #calculateSpeedPerPixel(android.util.DisplayMetrics)
*/
protected int calculateTimeForScrolling(int dx) {
// In a case where dx is very small, rounding may return 0 although dx > 0.
// To avoid that issue, ceil the result so that if dx > 0, we'll always return positive // time. return (int) Math.ceil(Math.abs(dx) * MILLISECONDS_PER_PX); } /** * <p>Calculates the time for deceleration so that transition from LinearInterpolator to * DecelerateInterpolator looks smooth.</p> * * @param dx Distance to scroll * @return Time for DecelerateInterpolator to smoothly traverse the distance when transitioning * from LinearInterpolation */ protected int calculateTimeForDeceleration(int dx) { // we want to cover same area with the linear interpolator for the first 10% of the // interpolation. After that, deceleration will take control. // area under curve (1-(1-x)^2) can be calculated as (1 - x/3) * x * x // which gives 0.100028 when x = .3356 // this is why we divide linear scrolling time with .3356 return (int) Math.ceil(calculateTimeForScrolling(dx) / .3356); } 复制代码
能够看到,第二个方法返回值越大,须要滚动的时间越长,也就是滚动越慢。
到这里,SnapHelper
的源码就分析完了,整理下思路,SnapHelper
辅助RecyclerView
实现滚动对齐就是经过给RecyclerView
设置OnScrollerListener
和OnFlingListener
这两个监听器实现的。 整个过程以下:
- 在
onFling
操做触发的时候首先经过findTargetSnapPosition
找到最终须要滚动到的位置,而后启动平滑滚动器滚动到指定位置,- 在指定位置须要渲染的View -targetView layout出来后,系统会回调
onTargetFound
,而后调用calculateDistanceToFinalSnap
方法计算targetView须要减速滚动的距离,而后经过Action
更新给滚动器。- 在滚动中止的时候,也就是state变成
SCROLL_STATE_IDLE
时会调用snapToTargetExistingView
,经过findSnapView
找到SnapView
,而后经过calculateDistanceToFinalSnap
计算获得滚动的距离,作最后的对齐调整。
前面分享的Demo就留到下一篇博客再说了,其实只要理解了SnapHelper
的源码,自定义就很简单了。
对Demo感兴趣的欢迎关注下一篇博客了。
完。