结合SwipeRefreshLayout可以上拉加载更多下拉刷新的RecyclerView
Posted Gradle官方文件
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了结合SwipeRefreshLayout可以上拉加载更多下拉刷新的RecyclerView相关的知识,希望对你有一定的参考价值。
源码下载地址:http://download.csdn.net/detail/zhou_anzhuojinjie/9661542
话不多说直接上代码
dependencies
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
exclude group: 'com.android.support', module: 'support-annotations'
)
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
compile 'com.android.support:recyclerview-v7:24.2.1'
PullRefreshLayout
package com.linzhou.recyclerviewfresh.refresh;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.support.annotation.ColorRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
/**
* Created by joe on 2016/10/23.
*/
public class PullRefreshLayout extends RelativeLayout
private int[] colors =
0xFFFF0000, 0xFFFF7F00, 0xFFFFFF00, 0xFF00FF00
, 0xFF00FFFF, 0xFF0000FF, 0xFF8B00FF;
private final int CIRCLE_BG_LIGHT = 0xFFFAFAFA;
private MaterialProgressDrawable mProgress;
private ValueAnimator mValueAnimator;
private boolean mStart = false;
private boolean mVisable = false;
private static final int PULL_IMAGE_SIZE = 40;
private static int PULL_IMAGE_SIZE_PX;//上拉View的大小(像素)
private static int PULL_IMAGE_SIZE_PX_MAX ;//最大拉动的距离
private static int PULL_IMAGE_SIZE_PX_EXECUTE ;//拉动到什么位置开始执行
private static int PULL_IMAGE_SIZE_PX_EXECUTE_REFRESH ;//刷新是所在的位置
private static float ROTATE_ANIM_ANGLE_PER;//根据最大距离计算旋转角度的比列
// private static final
private ImageView mImageView;
private boolean mIsFirst;
private int mStartY, mLastY;
private RecyclerView mRecyclerView;
//private int mFirstVisiblePosition;
private int mLastVisiblePosition;
private boolean mIsCanScoll;
private boolean mVisibleCanScoll;
private boolean mPrepareAnimation;//准备执行动画
private boolean mIsAllowLoadMore = true;//是否可以上拉刷新
private boolean mIsDispatch = true;//是否分发事件
public PullRefreshLayout(Context context)
this(context, null);
public PullRefreshLayout(Context context, AttributeSet attrs)
this(context, attrs, 0);
public PullRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr)
super(context, attrs, defStyleAttr);
/**
* 是否允许下拉加载更多
* @param allowLoadMore
*/
public void setAllowLoadMore(boolean allowLoadMore)
mIsAllowLoadMore = allowLoadMore;
public boolean isAllowLoadMore()
return mIsAllowLoadMore;
/**
* 设置进度圈的颜色
* @param colors 如:0xFFFF0000
*/
public void setColorSchemeColors(int... colors)
this.colors = colors;
/**
* 设置进度圈的颜色
* @param colorResIds 如:R.color.red
*/
public void setColorSchemeResources(@ColorRes int... colorResIds)
final Resources res = getResources();
int[] colorRes = new int[colorResIds.length];
for (int i = 0; i < colorResIds.length; i++)
colorRes[i] = res.getColor(colorResIds[i]);
setColorSchemeColors(colorRes);
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
super.onLayout(changed, l, t, r, b);
if (!mIsFirst)
createProgressView();
over:
for (int i = 0; i < getChildCount(); i++)
View childView = getChildAt(i);
if (childView instanceof SwipeRefreshLayout)
ViewGroup viewGroup = (ViewGroup) childView;
for (int j = 0; j < viewGroup.getChildCount(); j++)
View childViewJ = viewGroup.getChildAt(j);
if (childViewJ instanceof RecyclerView)
mRecyclerView = (RecyclerView) childViewJ;
break over;
if(childView instanceof RecyclerView)
mRecyclerView = (RecyclerView) childView;
break over;
mIsFirst = true;
@Override
public boolean dispatchTouchEvent(MotionEvent event)
if(!mIsAllowLoadMore) return super.dispatchTouchEvent(event);
switch (event.getAction())
case MotionEvent.ACTION_DOWN:
mStartY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
if (!mStart)
//如果不满足上拉的条件就直接分发事件
if(!canPullUp())
return super.dispatchTouchEvent(event);
if (canPullUp() && !mIsCanScoll)
showRefreshArrow();
mStartY = (int) event.getRawY();
mIsCanScoll = true;
else
//mStartY = (int) event.getRawY();
//hideRefreshArrow();
//hide();
if (mVisibleCanScoll)
int endY = (int) event.getRawY();
int offset = mStartY - endY;
//System.out.println("----------------------offset:" + offset);
LayoutParams lp = (LayoutParams) mImageView.getLayoutParams();
int bottomMargin = lp.bottomMargin;
bottomMargin += offset;
if (bottomMargin >= PULL_IMAGE_SIZE_PX_MAX)
bottomMargin = PULL_IMAGE_SIZE_PX_MAX;
if (bottomMargin <= -PULL_IMAGE_SIZE_PX)
bottomMargin = -PULL_IMAGE_SIZE_PX;
lp.setMargins(lp.leftMargin, lp.topMargin, lp.rightMargin, bottomMargin);
mImageView.setLayoutParams(lp);
rotateAniamtor(bottomMargin * ROTATE_ANIM_ANGLE_PER);
mStartY = endY;
LayoutParams lp = (LayoutParams) mImageView.getLayoutParams();
//如果按住上拉时,上拉箭头向下滑动的时候事件不应分发
if(mVisable && lp.bottomMargin > -PULL_IMAGE_SIZE_PX)
mIsDispatch = false;
else if(mVisable && lp.bottomMargin == -PULL_IMAGE_SIZE_PX)//等到上拉箭头被隐藏掉的时候在分发事件
mIsDispatch = true;
//是否分发事件
if(!mIsDispatch)
return false;
else
return super.dispatchTouchEvent(event);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (!mStart)
if (mVisibleCanScoll)
LayoutParams lp = (LayoutParams) mImageView.getLayoutParams();
if (lp.bottomMargin >= PULL_IMAGE_SIZE_PX_EXECUTE)
//lp.setMargins(lp.leftMargin, lp.topMargin, lp.rightMargin, PULL_IMAGE_SIZE_PX / 3 * 2);
//mImageView.setLayoutParams(lp);
//start();
getValueToTranslation();
mPrepareAnimation = true;
if (mOnPullListener != null)
mOnPullListener.onLoadMore(this);
else
hideArrow();
if (!mStart && !mPrepareAnimation)
hideArrow();
mIsCanScoll = false;
break;
return super.dispatchTouchEvent(event);
private void hideArrow()
LayoutParams lp = (LayoutParams) mImageView.getLayoutParams();
//lp.setMargins(lp.leftMargin, lp.topMargin, lp.rightMargin, -PULL_IMAGE_SIZE_PX);
//mImageView.setLayoutParams(lp);
translationTo(lp.bottomMargin,-PULL_IMAGE_SIZE_PX,false);
private void showRefreshArrow()
mImageView.setVisibility(View.VISIBLE);
visable();
/**
* 隐藏箭头显示的载体ImageView
*/
private void hideRefreshArrow()
mImageView.setVisibility(View.GONE);
private boolean canPullUp()
if(mRecyclerView == null || mRecyclerView.getAdapter() == null) return false;
RecyclerView.LayoutManager lm = mRecyclerView.getLayoutManager();
mLastVisiblePosition = getLastVisibleItemPosition();
int count = mRecyclerView.getAdapter().getItemCount();
if (0 == count)
// 没有item的时候也可以上拉加载
return true;
else if (mLastVisiblePosition == (count - 1))
// 滑到底部了
if (lm.findViewByPosition(count - 1).getBottom() <= getMeasuredHeight())
return true;
return false;
/**
* 获取底部可见项的位置
*
* @return
*/
private int getLastVisibleItemPosition()
RecyclerView.LayoutManager lm = mRecyclerView.getLayoutManager();
int lastVisibleItemPosition = 0;
if (lm instanceof GridLayoutManager)
lastVisibleItemPosition = ((GridLayoutManager) lm).findLastVisibleItemPosition();
else if (lm instanceof LinearLayoutManager)
lastVisibleItemPosition = ((LinearLayoutManager) lm).findLastVisibleItemPosition();
return lastVisibleItemPosition;
/**
* 创建刷新View和初始化一些数据
*/
private void createProgressView()
mImageView = new ImageView(getContext());
int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, PULL_IMAGE_SIZE, getContext().getResources().getDisplayMetrics());
PULL_IMAGE_SIZE_PX = size;
PULL_IMAGE_SIZE_PX_MAX = PULL_IMAGE_SIZE_PX * 2;
PULL_IMAGE_SIZE_PX_EXECUTE = PULL_IMAGE_SIZE_PX;
PULL_IMAGE_SIZE_PX_EXECUTE_REFRESH = PULL_IMAGE_SIZE_PX / 3 * 2;
ROTATE_ANIM_ANGLE_PER = (360.0f / PULL_IMAGE_SIZE_PX_MAX);
LayoutParams lp = new LayoutParams(size, size);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
lp.setMargins(lp.leftMargin, lp.topMargin, lp.rightMargin, -PULL_IMAGE_SIZE_PX);
mImageView.setLayoutParams(lp);
mImageView.setBackground(getShapeDrawable());
addView(mImageView);
mImageView.setVisibility(View.GONE);
mProgress = new MaterialProgressDrawable(getContext(), mImageView);
mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);
//圈圈颜色,可以是多种颜色
mProgress.setColorSchemeColors(colors);
//设置圈圈的各种大小
mProgress.updateSizes(MaterialProgressDrawable.LARGE);
mImageView.setImageDrawable(mProgress);
/**
* mImageView的背景
*/
private Drawable getShapeDrawable()
/**
* <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 第一层 上部和左部偏移一定距离-->
<item
>
<shape android:shape="oval">
<solid android:color="#f5f5f5" />
<!-- 描边 -->
<stroke
android:width="0.5dp"
android:color="#99f5f5f5" />
</shape>
</item>
<!-- 第二层 下部和有部偏移一定距离-->
<item
android:left="2dp"
android:top="2dp"
android:bottom="2dp"
android:right="2dp">
<shape android:shape="oval">
<solid android:color="#ffffff" />
<!-- 描边 -->
<!--<stroke android:width="0.33dp" android:color="#dedede" />-->
</shape>
</item>
</layer-list>
*/
//代码实现
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.OVAL);
gradientDrawable.setColor(Color.parseColor("#f5f5f5"));
int stroke = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0.5f, getContext().getResources().getDisplayMetrics());
gradientDrawable.setStroke(stroke,Color.parseColor("#99f5f5f5"));
GradientDrawable gradientDrawable2 = new GradientDrawable();
gradientDrawable2.setShape(GradientDrawable.OVAL);
gradientDrawable2.setColor(Color.parseColor("#ffffff"));
LayerDrawable drawable = new LayerDrawable(new Drawable[]gradientDrawable,gradientDrawable2);
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getContext().getResources().getDisplayMetrics());
drawable.setLayerInset(1,padding,padding,padding,padding);第一个参数1代表数组的第二个元素,为白色
return drawable;
/**
* 隐藏箭头
*/
private void hide()
if (mValueAnimator != null)
mValueAnimator.cancel();
mVisable = false;
mVisibleCanScoll = false;
private void visable()
if (mValueAnimator == null)
mValueAnimator = mValueAnimator.ofFloat(0f, 1f);
mValueAnimator.setDuration(10);
mValueAnimator.setInterpolator(new DecelerateInterpolator());
mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
@Override
public void onAnimationUpdate(ValueAnimator animation)
float n = (float) animation.getAnimatedValue();
//圈圈的旋转角度
mProgress.setProgressRotation(n * 0.5f);
//圈圈周长,0f-1F
mProgress.setStartEndTrim(0f, n * 0.8f);
//箭头大小,0f-1F
mProgress.setArrowScale(n);
//透明度,0-255
mProgress.setAlpha((int) (255 * n));
);
mValueAnimator.addListener(new AnimatorListenerAdapter()
@Override
public void onAnimationEnd(Animator animation)
super.onAnimationEnd(animation);
mVisable = true;
);
if (!mValueAnimator.isRunning())
if (!mVisable)
//是否显示箭头
mProgress.showArrow(true);
mValueAnimator.start();
mVisibleCanScoll = true;
private void start()
if (mVisable)
if (!mStart)
mProgress.start();
mStart = true;
/**
* 计算执行动画的距离参数
*/
private void getValueToTranslation()
//如果mImageView还没有被创建出来是不会执行的
if(mImageView != null)
LayoutParams lp = (LayoutParams) mImageView.getLayoutParams();
int bottomMargin = lp.bottomMargin;
//执行平移
translationTo(bottomMargin, PULL_IMAGE_SIZE_PX_EXECUTE_REFRESH, true);
private void stop()
if (mStart)
mProgress.stop();
mStart = false;
mVisable = false;
mVisibleCanScoll = false;
/**
* 执行平移动画
* @param from
* @param to
*/
private void translationTo(int from,int to,final boolean isShow)
//1.调用ofInt(int...values)方法创建ValueAnimator对象
ValueAnimator mAnimator = ValueAnimator.ofInt(from,to);
//2.为目标对象的属性变化设置监听器
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
@Override
public void onAnimationUpdate(ValueAnimator animation)
// 3.为目标对象的属性设置计算好的属性值
int animatorValue = (int)animation.getAnimatedValue();
MarginLayoutParams marginLayoutParams = (MarginLayoutParams) mImageView.getLayoutParams();
marginLayoutParams.bottomMargin = animatorValue;
mImageView.setLayoutParams(marginLayoutParams);
);
mAnimator.addListener(new AnimatorListenerAdapter()
@Override
public void onAnimationEnd(Animator animation)
super.onAnimationEnd(animation);
if(isShow)
start();
mPrepareAnimation = false;
else
hideRefreshArrow();
hide();
);
//4.设置动画的持续时间、是否重复及重复次数等属性
mAnimator.setDuration(100);
//mAnimator.setRepeatCount(3);
mAnimator.setRepeatMode(ValueAnimator.INFINITE);
//5.为ValueAnimator设置目标对象并开始执行动画
mAnimator.setTarget(mImageView);
mAnimator.start();
/**
* 旋转动画效果
*/
private void rotateAniamtor(float from)
ObjectAnimator mAnimatorRotate = ObjectAnimator.ofFloat(mImageView, "rotation",from,from + 1);
mAnimatorRotate.setRepeatMode(Animation.INFINITE);
mAnimatorRotate.setRepeatCount(1);
mAnimatorRotate.setDuration(10);
mAnimatorRotate.start();
/**
* 加载更多或停止加载更多
* @param refreshing
*/
public void setRefreshing(boolean refreshing)
if(!mIsAllowLoadMore) return;
if(refreshing)
if(mStart) return;
showRefreshArrow();
getValueToTranslation();
mPrepareAnimation = true;
if (mOnPullListener != null)
mOnPullListener.onLoadMore(this);
mIsCanScoll = false;
else
stop();
hideArrow();
/**
* 当前是否在上拉刷新
* @return
*/
public boolean isRefreshing()
return mStart;
/**
* 刷新加载回调接口
*
* @author chenjing
*/
public interface OnPullListener
/**
* 加载操作
*/
void onLoadMore(PullRefreshLayout pullRefreshLayout);
private OnPullListener mOnPullListener;
public void setOnPullListener(OnPullListener listener)
mOnPullListener = listener;
MaterialProgressDrawable
package com.linzhou.recyclerviewfresh.refresh;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
/**
* Created by joe on 2016/10/23.
*/
public class MaterialProgressDrawable extends Drawable implements Animatable
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
private static final Interpolator MATERIAL_INTERPOLATOR = new FastOutSlowInInterpolator();
private static final float FULL_ROTATION = 1080.0f;
@Retention(RetentionPolicy.CLASS)
@IntDef(LARGE, DEFAULT)
public @interface ProgressDrawableSize
// Maps to ProgressBar.Large style
public static final int LARGE = 0;
// Maps to ProgressBar default style
public static final int DEFAULT = 1;
// Maps to ProgressBar default style
private static final int CIRCLE_DIAMETER = 40;
private static final float CENTER_RADIUS = 8.75f; //should add up to 10 when + stroke_width
private static final float STROKE_WIDTH = 2.5f;
// Maps to ProgressBar.Large style
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float CENTER_RADIUS_LARGE = 12.5f;
private static final float STROKE_WIDTH_LARGE = 3f;
private final int[] COLORS = new int[]
Color.BLACK
;
/**
* The value in the linear interpolator for animating the drawable at which
* the color transition should start
*/
private static final float COLOR_START_DELAY_OFFSET = 0.75f;
private static final float END_TRIM_START_DELAY_OFFSET = 0.5f;
private static final float START_TRIM_DURATION_OFFSET = 0.5f;
/** The duration of a single progress spin in milliseconds. */
private static final int ANIMATION_DURATION = 1332;
/** The number of points in the progress "star". */
private static final float NUM_POINTS = 5f;
/** The list of animators operating on this drawable. */
private final ArrayList<Animation> mAnimators = new ArrayList<>();
/** The indicator ring, used to manage animation state. */
private final Ring mRing;
/** Canvas rotation in degrees. */
private float mRotation;
/** Layout info for the arrowhead in dp */
private static final int ARROW_WIDTH = 10;
private static final int ARROW_HEIGHT = 5;
private static final float ARROW_OFFSET_ANGLE = 5;
/** Layout info for the arrowhead for the large spinner in dp */
private static final int ARROW_WIDTH_LARGE = 12;
private static final int ARROW_HEIGHT_LARGE = 6;
private static final float MAX_PROGRESS_ARC = .8f;
private Resources mResources;
private View mParent;
private Animation mAnimation;
private float mRotationCount;
private double mWidth;
private double mHeight;
boolean mFinishing;
public MaterialProgressDrawable(Context context, View parent)
mParent = parent;
mResources = context.getResources();
mRing = new Ring(mCallback);
mRing.setColors(COLORS);
updateSizes(DEFAULT);
setupAnimators();
private void setSizeParameters(double progressCircleWidth, double progressCircleHeight,
double centerRadius, double strokeWidth, float arrowWidth, float arrowHeight)
final Ring ring = mRing;
final DisplayMetrics metrics = mResources.getDisplayMetrics();
final float screenDensity = metrics.density;
mWidth = progressCircleWidth * screenDensity;
mHeight = progressCircleHeight * screenDensity;
ring.setStrokeWidth((float) strokeWidth * screenDensity);
ring.setCenterRadius(centerRadius * screenDensity);
ring.setColorIndex(0);
ring.setArrowDimensions(arrowWidth * screenDensity, arrowHeight * screenDensity);
ring.setInsets((int) mWidth, (int) mHeight);
public void updateSizes(@ProgressDrawableSize int size)
if (size == LARGE)
setSizeParameters(CIRCLE_DIAMETER_LARGE, CIRCLE_DIAMETER_LARGE, CENTER_RADIUS_LARGE,
STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE, ARROW_HEIGHT_LARGE);
else
setSizeParameters(CIRCLE_DIAMETER, CIRCLE_DIAMETER, CENTER_RADIUS, STROKE_WIDTH,
ARROW_WIDTH, ARROW_HEIGHT);
/**
* @param show Set to true to display the arrowhead on the progress spinner.
*/
public void showArrow(boolean show)
mRing.setShowArrow(show);
/**
* @param scale Set the scale of the arrowhead for the spinner.
*/
public void setArrowScale(float scale)
mRing.setArrowScale(scale);
/**
* Set the start and end trim for the progress spinner arc.
*
* @param startAngle start angle
* @param endAngle end angle
*/
public void setStartEndTrim(float startAngle, float endAngle)
mRing.setStartTrim(startAngle);
mRing.setEndTrim(endAngle);
/**
* Set the amount of rotation to apply to the progress spinner.
*
* @param rotation Rotation is from [0..1]
*/
public void setProgressRotation(float rotation)
mRing.setRotation(rotation);
/**
* Update the background color of the circle image view.
*/
public void setBackgroundColor(int color)
mRing.setBackgroundColor(color);
/**
* Set the colors used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors)
mRing.setColors(colors);
mRing.setColorIndex(0);
@Override
public int getIntrinsicHeight()
return (int) mHeight;
@Override
public int getIntrinsicWidth()
return (int) mWidth;
@Override
public void draw(Canvas c)
final Rect bounds = getBounds();
final int saveCount = c.save();
c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
mRing.draw(c, bounds);
c.restoreToCount(saveCount);
@Override
public void setAlpha(int alpha)
mRing.setAlpha(alpha);
public int getAlpha()
return mRing.getAlpha();
@Override
public void setColorFilter(ColorFilter colorFilter)
mRing.setColorFilter(colorFilter);
@SuppressWarnings("unused")
void setRotation(float rotation)
mRotation = rotation;
invalidateSelf();
@SuppressWarnings("unused")
private float getRotation()
return mRotation;
@Override
public int getOpacity()
return PixelFormat.TRANSLUCENT;
@Override
public boolean isRunning()
final ArrayList<Animation> animators = mAnimators;
final int N = animators.size();
for (int i = 0; i < N; i++)
final Animation animator = animators.get(i);
if (animator.hasStarted() && !animator.hasEnded())
return true;
return false;
@Override
public void start()
mAnimation.reset();
mRing.storeOriginals();
// Already showing some part of the ring
if (mRing.getEndTrim() != mRing.getStartTrim())
mFinishing = true;
mAnimation.setDuration(ANIMATION_DURATION/2);
mParent.startAnimation(mAnimation);
else
mRing.setColorIndex(0);
mRing.resetOriginals();
mAnimation.setDuration(ANIMATION_DURATION);
mParent.startAnimation(mAnimation);
@Override
public void stop()
mParent.clearAnimation();
setRotation(0);
mRing.setShowArrow(false);
mRing.setColorIndex(0);
mRing.resetOriginals();
private float getMinProgressArc(Ring ring)
return (float) Math.toRadians(
ring.getStrokeWidth() / (2 * Math.PI * ring.getCenterRadius()));
// Adapted from ArgbEvaluator.java
private int evaluateColorChange(float fraction, int startValue, int endValue)
int startInt = (Integer) startValue;
int startA = (startInt >> 24) & 0xff;
int startR = (startInt >> 16) & 0xff;
int startG = (startInt >> 8) & 0xff;
int startB = startInt & 0xff;
int endInt = (Integer) endValue;
int endA = (endInt >> 24) & 0xff;
int endR = (endInt >> 16) & 0xff;
int endG = (endInt >> 8) & 0xff;
int endB = endInt & 0xff;
return (int)((startA + (int)(fraction * (endA - startA))) << 24) |
(int)((startR + (int)(fraction * (endR - startR))) << 16) |
(int)((startG + (int)(fraction * (endG - startG))) << 8) |
(int)((startB + (int)(fraction * (endB - startB))));
/**
* Update the ring color if this is within the last 25% of the animation.
* The new ring color will be a translation from the starting ring color to
* the next color.
*/
private void updateRingColor(float interpolatedTime, Ring ring)
if (interpolatedTime > COLOR_START_DELAY_OFFSET)
// scale the interpolatedTime so that the full
// transformation from 0 - 1 takes place in the
// remaining time
ring.setColor(evaluateColorChange((interpolatedTime - COLOR_START_DELAY_OFFSET)
/ (1.0f - COLOR_START_DELAY_OFFSET), ring.getStartingColor(),
ring.getNextColor()));
private void applyFinishTranslation(float interpolatedTime, Ring ring)
// shrink back down and complete a full rotation before
// starting other circles
// Rotation goes between [0..1].
updateRingColor(interpolatedTime, ring);
float targetRotation = (float) (Math.floor(ring.getStartingRotation() / MAX_PROGRESS_ARC)
+ 1f);
final float minProgressArc = getMinProgressArc(ring);
final float startTrim = ring.getStartingStartTrim()
+ (ring.getStartingEndTrim() - minProgressArc - ring.getStartingStartTrim())
* interpolatedTime;
ring.setStartTrim(startTrim);
ring.setEndTrim(ring.getStartingEndTrim());
final float rotation = ring.getStartingRotation()
+ ((targetRotation - ring.getStartingRotation()) * interpolatedTime);
ring.setRotation(rotation);
private void setupAnimators()
final Ring ring = mRing;
final Animation animation = new Animation()
@Override
public void applyTransformation(float interpolatedTime, Transformation t)
if (mFinishing)
applyFinishTranslation(interpolatedTime, ring);
else
// The minProgressArc is calculated from 0 to create an
// angle that matches the stroke width.
final float minProgressArc = getMinProgressArc(ring);
final float startingEndTrim = ring.getStartingEndTrim();
final float startingTrim = ring.getStartingStartTrim();
final float startingRotation = ring.getStartingRotation();
updateRingColor(interpolatedTime, ring);
// Moving the start trim only occurs in the first 50% of a
// single ring animation
if (interpolatedTime <= START_TRIM_DURATION_OFFSET)
// scale the interpolatedTime so that the full
// transformation from 0 - 1 takes place in the
以上是关于结合SwipeRefreshLayout可以上拉加载更多下拉刷新的RecyclerView的主要内容,如果未能解决你的问题,请参考以下文章
使用SwipeRefreshLayout和RecyclerView实现仿“简书”下拉刷新和上拉加载更多
使用SwipeRefreshLayout和RecyclerView实现仿“简书”下拉刷新和上拉加载更多
使用SwipeRefreshLayout和RecyclerView实现仿“简书”下拉刷新和上拉加载更多
[Android实例] Android 6.0RecyclerView SwipeRefreshLayout 下拉刷新 上拉加载
Android 使用SwipeRefreshLayout实现RecyclerVeiw的下拉刷新和上拉加载
FastDev4Android框架开发RecyclerView完全解析之下拉刷新与上拉加载SwipeRefreshLayout(三十一)