SwipeRefreshLayout.java revision 07a4db40e79aae23694b205f99b013ee2e4f2307
1/* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.support.v4.widget; 18 19import android.content.Context; 20import android.content.res.Resources; 21import android.content.res.TypedArray; 22import android.support.v4.view.MotionEventCompat; 23import android.support.v4.view.ViewCompat; 24import android.util.AttributeSet; 25import android.util.DisplayMetrics; 26import android.util.Log; 27import android.view.MotionEvent; 28import android.view.View; 29import android.view.ViewConfiguration; 30import android.view.ViewGroup; 31import android.view.animation.Animation; 32import android.view.animation.Animation.AnimationListener; 33import android.view.animation.DecelerateInterpolator; 34import android.view.animation.Transformation; 35import android.widget.AbsListView; 36 37/** 38 * The SwipeRefreshLayout should be used whenever the user can refresh the 39 * contents of a view via a vertical swipe gesture. The activity that 40 * instantiates this view should add an OnRefreshListener to be notified 41 * whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout 42 * will notify the listener each and every time the gesture is completed again; 43 * the listener is responsible for correctly determining when to actually 44 * initiate a refresh of its content. If the listener determines there should 45 * not be a refresh, it must call setRefreshing(false) to cancel any visual 46 * indication of a refresh. If an activity wishes to show just the progress 47 * animation, it should call setRefreshing(true). To disable the gesture and 48 * progress animation, call setEnabled(false) on the view. 49 * <p> 50 * This layout should be made the parent of the view that will be refreshed as a 51 * result of the gesture and can only support one direct child. This view will 52 * also be made the target of the gesture and will be forced to match both the 53 * width and the height supplied in this layout. The SwipeRefreshLayout does not 54 * provide accessibility events; instead, a menu item must be provided to allow 55 * refresh of the content wherever this gesture is used. 56 * </p> 57 */ 58public class SwipeRefreshLayout extends ViewGroup { 59 // Maps to ProgressBar.Large style 60 public static final int LARGE = MaterialProgressDrawable.LARGE; 61 // Maps to ProgressBar default style 62 public static final int DEFAULT = MaterialProgressDrawable.DEFAULT; 63 64 private static final String LOG_TAG = SwipeRefreshLayout.class.getSimpleName(); 65 66 private static final int MAX_ALPHA = 255; 67 private static final int STARTING_PROGRESS_ALPHA = (int) (.3f * MAX_ALPHA); 68 69 private static final int CIRCLE_DIAMETER = 40; 70 private static final int CIRCLE_DIAMETER_LARGE = 56; 71 72 private static final float DECELERATE_INTERPOLATION_FACTOR = 2f; 73 private static final int INVALID_POINTER = -1; 74 private static final float DRAG_RATE = .5f; 75 76 // Max amount of circle that can be filled by progress during swipe gesture, 77 // where 1.0 is a full circle 78 private static final float MAX_PROGRESS_ANGLE = .8f; 79 80 private static final int SCALE_DOWN_DURATION = 150; 81 82 private static final int ALPHA_ANIMATION_DURATION = 300; 83 84 private static final int ANIMATE_TO_TRIGGER_DURATION = 200; 85 86 private static final int ANIMATE_TO_START_DURATION = 200; 87 88 // Default background for the progress spinner 89 private static final int CIRCLE_BG_LIGHT = 0xFFFAFAFA; 90 // Default offset in dips from the top of the view to where the progress spinner should stop 91 private static final int DEFAULT_CIRCLE_TARGET = 64; 92 93 private View mTarget; // the target of the gesture 94 private OnRefreshListener mListener; 95 private boolean mRefreshing = false; 96 private int mTouchSlop; 97 private float mTotalDragDistance = -1; 98 private int mMediumAnimationDuration; 99 private int mCurrentTargetOffsetTop; 100 // Whether or not the starting offset has been determined. 101 private boolean mOriginalOffsetCalculated = false; 102 103 private float mInitialMotionY; 104 private boolean mIsBeingDragged; 105 private int mActivePointerId = INVALID_POINTER; 106 // Whether this item is scaled up rather than clipped 107 private boolean mScale; 108 109 // Target is returning to its start offset because it was cancelled or a 110 // refresh was triggered. 111 private boolean mReturningToStart; 112 private final DecelerateInterpolator mDecelerateInterpolator; 113 private static final int[] LAYOUT_ATTRS = new int[] { 114 android.R.attr.enabled 115 }; 116 117 private CircleImageView mCircleView; 118 private int mCircleViewIndex = -1; 119 120 protected int mFrom; 121 122 private float mStartingScale; 123 124 protected int mOriginalOffsetTop; 125 126 private MaterialProgressDrawable mProgress; 127 128 private Animation mScaleAnimation; 129 130 private Animation mScaleDownAnimation; 131 132 private Animation mAlphaStartAnimation; 133 134 private Animation mAlphaMaxAnimation; 135 136 private Animation mScaleDownToStartAnimation; 137 138 private float mSpinnerFinalOffset; 139 140 private boolean mNotify; 141 142 private int mCircleWidth; 143 144 private int mCircleHeight; 145 146 // Whether the client has set a custom starting position; 147 private boolean mUsingCustomStart; 148 149 private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() { 150 @Override 151 public void onAnimationStart(Animation animation) { 152 } 153 154 @Override 155 public void onAnimationRepeat(Animation animation) { 156 } 157 158 @Override 159 public void onAnimationEnd(Animation animation) { 160 if (mRefreshing) { 161 // Make sure the progress view is fully visible 162 mProgress.setAlpha(MAX_ALPHA); 163 mProgress.start(); 164 if (mNotify) { 165 if (mListener != null) { 166 mListener.onRefresh(); 167 } 168 } 169 } else { 170 mProgress.stop(); 171 mCircleView.setVisibility(View.GONE); 172 setColorViewAlpha(MAX_ALPHA); 173 // Return the circle to its start position 174 if (mScale) { 175 setAnimationProgress(0 /* animation complete and view is hidden */); 176 } else { 177 setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCurrentTargetOffsetTop, 178 true /* requires update */); 179 } 180 } 181 mCurrentTargetOffsetTop = mCircleView.getTop(); 182 } 183 }; 184 185 private void setColorViewAlpha(int targetAlpha) { 186 mCircleView.getBackground().setAlpha(targetAlpha); 187 mProgress.setAlpha(targetAlpha); 188 } 189 190 /** 191 * The refresh indicator starting and resting position is always positioned 192 * near the top of the refreshing content. This position is a consistent 193 * location, but can be adjusted in either direction based on whether or not 194 * there is a toolbar or actionbar present. 195 * 196 * @param scale Set to true if there is no view at a higher z-order than 197 * where the progress spinner is set to appear. 198 * @param start The offset in pixels from the top of this view at which the 199 * progress spinner should appear. 200 * @param end The offset in pixels from the top of this view at which the 201 * progress spinner should come to rest after a successful swipe 202 * gesture. 203 */ 204 public void setProgressViewOffset(boolean scale, int start, int end) { 205 mScale = scale; 206 mCircleView.setVisibility(View.GONE); 207 mOriginalOffsetTop = mCurrentTargetOffsetTop = start; 208 mSpinnerFinalOffset = end; 209 mUsingCustomStart = true; 210 mCircleView.invalidate(); 211 } 212 213 /** 214 * The refresh indicator resting position is always positioned near the top 215 * of the refreshing content. This position is a consistent location, but 216 * can be adjusted in either direction based on whether or not there is a 217 * toolbar or actionbar present. 218 * 219 * @param scale Set to true if there is no view at a higher z-order than 220 * where the progress spinner is set to appear. 221 * @param end The offset in pixels from the top of this view at which the 222 * progress spinner should come to rest after a successful swipe 223 * gesture. 224 */ 225 public void setProgressViewEndTarget(boolean scale, int end) { 226 mSpinnerFinalOffset = end; 227 mScale = scale; 228 mCircleView.invalidate(); 229 } 230 231 /** 232 * One of DEFAULT, or LARGE. 233 */ 234 public void setSize(int size) { 235 if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) { 236 return; 237 } 238 final DisplayMetrics metrics = getResources().getDisplayMetrics(); 239 if (size == MaterialProgressDrawable.LARGE) { 240 mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density); 241 } else { 242 mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density); 243 } 244 // force the bounds of the progress circle inside the circle view to 245 // update by setting it to null before updating its size and then 246 // re-setting it 247 mCircleView.setImageDrawable(null); 248 mProgress.updateSizes(size); 249 mCircleView.setImageDrawable(mProgress); 250 } 251 252 /** 253 * Simple constructor to use when creating a SwipeRefreshLayout from code. 254 * 255 * @param context 256 */ 257 public SwipeRefreshLayout(Context context) { 258 this(context, null); 259 } 260 261 /** 262 * Constructor that is called when inflating SwipeRefreshLayout from XML. 263 * 264 * @param context 265 * @param attrs 266 */ 267 public SwipeRefreshLayout(Context context, AttributeSet attrs) { 268 super(context, attrs); 269 270 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 271 272 mMediumAnimationDuration = getResources().getInteger( 273 android.R.integer.config_mediumAnimTime); 274 275 setWillNotDraw(false); 276 mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR); 277 278 final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS); 279 setEnabled(a.getBoolean(0, true)); 280 a.recycle(); 281 282 final DisplayMetrics metrics = getResources().getDisplayMetrics(); 283 mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density); 284 mCircleHeight = (int) (CIRCLE_DIAMETER * metrics.density); 285 286 createProgressView(); 287 ViewCompat.setChildrenDrawingOrderEnabled(this, true); 288 // the absolute offset has to take into account that the circle starts at an offset 289 mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density; 290 mTotalDragDistance = mSpinnerFinalOffset; 291 } 292 293 protected int getChildDrawingOrder(int childCount, int i) { 294 if (mCircleViewIndex < 0) { 295 return i; 296 } else if (i == childCount - 1) { 297 // Draw the selected child last 298 return mCircleViewIndex; 299 } else if (i >= mCircleViewIndex) { 300 // Move the children after the selected child earlier one 301 return i + 1; 302 } else { 303 // Keep the children before the selected child the same 304 return i; 305 } 306 } 307 308 private void createProgressView() { 309 mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT, CIRCLE_DIAMETER/2); 310 mProgress = new MaterialProgressDrawable(getContext(), this); 311 mProgress.setBackgroundColor(CIRCLE_BG_LIGHT); 312 mCircleView.setImageDrawable(mProgress); 313 mCircleView.setVisibility(View.GONE); 314 addView(mCircleView); 315 } 316 317 /** 318 * Set the listener to be notified when a refresh is triggered via the swipe 319 * gesture. 320 */ 321 public void setOnRefreshListener(OnRefreshListener listener) { 322 mListener = listener; 323 } 324 325 /** 326 * Pre API 11, alpha is used to make the progress circle appear instead of scale. 327 */ 328 private boolean isAlphaUsedForScale() { 329 return android.os.Build.VERSION.SDK_INT < 11; 330 } 331 332 /** 333 * Notify the widget that refresh state has changed. Do not call this when 334 * refresh is triggered by a swipe gesture. 335 * 336 * @param refreshing Whether or not the view should show refresh progress. 337 */ 338 public void setRefreshing(boolean refreshing) { 339 if (refreshing && mRefreshing != refreshing) { 340 // scale and show 341 mRefreshing = refreshing; 342 int endTarget = 0; 343 if (!mUsingCustomStart) { 344 endTarget = (int) (mSpinnerFinalOffset + mOriginalOffsetTop); 345 } else { 346 endTarget = (int) mSpinnerFinalOffset; 347 } 348 setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop, 349 true /* requires update */); 350 mNotify = false; 351 startScaleUpAnimation(mRefreshListener); 352 } else { 353 setRefreshing(refreshing, false /* notify */); 354 } 355 } 356 357 private void startScaleUpAnimation(AnimationListener listener) { 358 mCircleView.setVisibility(View.VISIBLE); 359 if (android.os.Build.VERSION.SDK_INT >= 11) { 360 // Pre API 11, alpha is used in place of scale up to show the 361 // progress circle appearing. 362 // Don't adjust the alpha during appearance otherwise. 363 mProgress.setAlpha(MAX_ALPHA); 364 } 365 mScaleAnimation = new Animation() { 366 @Override 367 public void applyTransformation(float interpolatedTime, Transformation t) { 368 setAnimationProgress(interpolatedTime); 369 } 370 }; 371 mScaleAnimation.setDuration(mMediumAnimationDuration); 372 if (listener != null) { 373 mCircleView.setAnimationListener(listener); 374 } 375 mCircleView.clearAnimation(); 376 mCircleView.startAnimation(mScaleAnimation); 377 } 378 379 /** 380 * Pre API 11, this does an alpha animation. 381 * @param progress 382 */ 383 private void setAnimationProgress(float progress) { 384 if (isAlphaUsedForScale()) { 385 setColorViewAlpha((int) (progress * MAX_ALPHA)); 386 } else { 387 ViewCompat.setScaleX(mCircleView, progress); 388 ViewCompat.setScaleY(mCircleView, progress); 389 } 390 } 391 392 private void setRefreshing(boolean refreshing, final boolean notify) { 393 if (mRefreshing != refreshing) { 394 mNotify = notify; 395 ensureTarget(); 396 mRefreshing = refreshing; 397 if (mRefreshing) { 398 animateOffsetToCorrectPosition(mCurrentTargetOffsetTop, mRefreshListener); 399 } else { 400 startScaleDownAnimation(mRefreshListener); 401 } 402 } 403 } 404 405 private void startScaleDownAnimation(Animation.AnimationListener listener) { 406 mScaleDownAnimation = new Animation() { 407 @Override 408 public void applyTransformation(float interpolatedTime, Transformation t) { 409 setAnimationProgress(1 - interpolatedTime); 410 } 411 }; 412 mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION); 413 mCircleView.setAnimationListener(listener); 414 mCircleView.clearAnimation(); 415 mCircleView.startAnimation(mScaleDownAnimation); 416 } 417 418 private void startProgressAlphaStartAnimation() { 419 mAlphaStartAnimation = startAlphaAnimation(mProgress.getAlpha(), STARTING_PROGRESS_ALPHA); 420 } 421 422 private void startProgressAlphaMaxAnimation() { 423 mAlphaMaxAnimation = startAlphaAnimation(mProgress.getAlpha(), MAX_ALPHA); 424 } 425 426 private Animation startAlphaAnimation(final int startingAlpha, final int endingAlpha) { 427 // Pre API 11, alpha is used in place of scale. Don't also use it to 428 // show the trigger point. 429 if (mScale && isAlphaUsedForScale()) { 430 return null; 431 } 432 Animation alpha = new Animation() { 433 @Override 434 public void applyTransformation(float interpolatedTime, Transformation t) { 435 mProgress 436 .setAlpha((int) (startingAlpha+ ((endingAlpha - startingAlpha) 437 * interpolatedTime))); 438 } 439 }; 440 alpha.setDuration(ALPHA_ANIMATION_DURATION); 441 // Clear out the previous animation listeners. 442 mCircleView.setAnimationListener(null); 443 mCircleView.clearAnimation(); 444 mCircleView.startAnimation(alpha); 445 return alpha; 446 } 447 448 /** 449 * Set the background color of the progress spinner disc. 450 * 451 * @param colorRes Resource id of the color. 452 */ 453 public void setProgressBackgroundColor(int colorRes) { 454 mCircleView.setBackgroundColor(colorRes); 455 mProgress.setBackgroundColor(getResources().getColor(colorRes)); 456 } 457 458 /** 459 * @deprecated Use {@link #setColorSchemeResources(int...)} 460 */ 461 @Deprecated 462 public void setColorScheme(int... colors) { 463 setColorSchemeResources(colors); 464 } 465 466 /** 467 * Set the color resources used in the progress animation from color resources. 468 * The first color will also be the color of the bar that grows in response 469 * to a user swipe gesture. 470 * 471 * @param colorResIds 472 */ 473 public void setColorSchemeResources(int... colorResIds) { 474 final Resources res = getResources(); 475 int[] colorRes = new int[colorResIds.length]; 476 for (int i = 0; i < colorResIds.length; i++) { 477 colorRes[i] = res.getColor(colorResIds[i]); 478 } 479 setColorSchemeColors(colorRes); 480 } 481 482 /** 483 * Set the colors used in the progress animation. The first 484 * color will also be the color of the bar that grows in response to a user 485 * swipe gesture. 486 * 487 * @param colors 488 */ 489 public void setColorSchemeColors(int... colors) { 490 ensureTarget(); 491 mProgress.setColorSchemeColors(colors); 492 } 493 494 /** 495 * @return Whether the SwipeRefreshWidget is actively showing refresh 496 * progress. 497 */ 498 public boolean isRefreshing() { 499 return mRefreshing; 500 } 501 502 private void ensureTarget() { 503 // Don't bother getting the parent height if the parent hasn't been laid 504 // out yet. 505 if (mTarget == null) { 506 for (int i = 0; i < getChildCount(); i++) { 507 View child = getChildAt(i); 508 if (!child.equals(mCircleView)) { 509 mTarget = child; 510 break; 511 } 512 } 513 } 514 } 515 516 /** 517 * Set the distance to trigger a sync in dips 518 * 519 * @param distance 520 */ 521 public void setDistanceToTriggerSync(int distance) { 522 mTotalDragDistance = distance; 523 } 524 525 @Override 526 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 527 final int width = getMeasuredWidth(); 528 final int height = getMeasuredHeight(); 529 if (getChildCount() == 0) { 530 return; 531 } 532 if (mTarget == null) { 533 ensureTarget(); 534 } 535 if (mTarget == null) { 536 return; 537 } 538 final View child = mTarget; 539 final int childLeft = getPaddingLeft(); 540 final int childTop = getPaddingTop(); 541 final int childWidth = width - getPaddingLeft() - getPaddingRight(); 542 final int childHeight = height - getPaddingTop() - getPaddingBottom(); 543 child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); 544 int circleWidth = mCircleView.getMeasuredWidth(); 545 int circleHeight = mCircleView.getMeasuredHeight(); 546 mCircleView.layout((width / 2 - circleWidth / 2), mCurrentTargetOffsetTop, 547 (width / 2 + circleWidth / 2), mCurrentTargetOffsetTop + circleHeight); 548 } 549 550 @Override 551 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 552 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 553 if (mTarget == null) { 554 ensureTarget(); 555 } 556 if (mTarget == null) { 557 return; 558 } 559 mTarget.measure(MeasureSpec.makeMeasureSpec( 560 getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), 561 MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec( 562 getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY)); 563 mCircleView.measure(MeasureSpec.makeMeasureSpec(mCircleWidth, MeasureSpec.EXACTLY), 564 MeasureSpec.makeMeasureSpec(mCircleHeight, MeasureSpec.EXACTLY)); 565 if (!mUsingCustomStart && !mOriginalOffsetCalculated) { 566 mOriginalOffsetCalculated = true; 567 mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight(); 568 } 569 mCircleViewIndex = -1; 570 // Get the index of the circleview. 571 for (int index = 0; index < getChildCount(); index++) { 572 if (getChildAt(index) == mCircleView) { 573 mCircleViewIndex = index; 574 break; 575 } 576 } 577 } 578 579 /** 580 * @return Whether it is possible for the child view of this layout to 581 * scroll up. Override this if the child view is a custom view. 582 */ 583 public boolean canChildScrollUp() { 584 if (android.os.Build.VERSION.SDK_INT < 14) { 585 if (mTarget instanceof AbsListView) { 586 final AbsListView absListView = (AbsListView) mTarget; 587 return absListView.getChildCount() > 0 588 && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0) 589 .getTop() < absListView.getPaddingTop()); 590 } else { 591 return mTarget.getScrollY() > 0; 592 } 593 } else { 594 return ViewCompat.canScrollVertically(mTarget, -1); 595 } 596 } 597 598 @Override 599 public boolean onInterceptTouchEvent(MotionEvent ev) { 600 ensureTarget(); 601 602 final int action = MotionEventCompat.getActionMasked(ev); 603 604 if (mReturningToStart && action == MotionEvent.ACTION_DOWN) { 605 mReturningToStart = false; 606 } 607 608 if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing) { 609 // Fail fast if we're not in a state where a swipe is possible 610 return false; 611 } 612 613 switch (action) { 614 case MotionEvent.ACTION_DOWN: 615 setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCircleView.getTop(), true); 616 mActivePointerId = MotionEventCompat.getPointerId(ev, 0); 617 mIsBeingDragged = false; 618 final float initialMotionY = getMotionEventY(ev, mActivePointerId); 619 if (initialMotionY == -1) { 620 return false; 621 } 622 mInitialMotionY = initialMotionY; 623 624 case MotionEvent.ACTION_MOVE: 625 if (mActivePointerId == INVALID_POINTER) { 626 Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id."); 627 return false; 628 } 629 630 final float y = getMotionEventY(ev, mActivePointerId); 631 if (y == -1) { 632 return false; 633 } 634 final float yDiff = y - mInitialMotionY; 635 if (yDiff > mTouchSlop && !mIsBeingDragged) { 636 mIsBeingDragged = true; 637 mProgress.setAlpha(STARTING_PROGRESS_ALPHA); 638 } 639 break; 640 641 case MotionEventCompat.ACTION_POINTER_UP: 642 onSecondaryPointerUp(ev); 643 break; 644 645 case MotionEvent.ACTION_UP: 646 case MotionEvent.ACTION_CANCEL: 647 mIsBeingDragged = false; 648 mActivePointerId = INVALID_POINTER; 649 break; 650 } 651 652 return mIsBeingDragged; 653 } 654 655 private float getMotionEventY(MotionEvent ev, int activePointerId) { 656 final int index = MotionEventCompat.findPointerIndex(ev, activePointerId); 657 if (index < 0) { 658 return -1; 659 } 660 return MotionEventCompat.getY(ev, index); 661 } 662 663 @Override 664 public void requestDisallowInterceptTouchEvent(boolean b) { 665 // Nope. 666 } 667 668 private boolean isAnimationRunning(Animation animation) { 669 return animation != null && animation.hasStarted() && !animation.hasEnded(); 670 } 671 672 @Override 673 public boolean onTouchEvent(MotionEvent ev) { 674 final int action = MotionEventCompat.getActionMasked(ev); 675 676 if (mReturningToStart && action == MotionEvent.ACTION_DOWN) { 677 mReturningToStart = false; 678 } 679 680 if (!isEnabled() || mReturningToStart || canChildScrollUp()) { 681 // Fail fast if we're not in a state where a swipe is possible 682 return false; 683 } 684 685 switch (action) { 686 case MotionEvent.ACTION_DOWN: 687 mActivePointerId = MotionEventCompat.getPointerId(ev, 0); 688 mIsBeingDragged = false; 689 break; 690 691 case MotionEvent.ACTION_MOVE: { 692 final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); 693 if (pointerIndex < 0) { 694 Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id."); 695 return false; 696 } 697 698 final float y = MotionEventCompat.getY(ev, pointerIndex); 699 final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE; 700 if (mIsBeingDragged) { 701 mProgress.showArrow(true); 702 float originalDragPercent = overscrollTop / mTotalDragDistance; 703 if (originalDragPercent < 0) { 704 return false; 705 } 706 float dragPercent = Math.min(1f, Math.abs(originalDragPercent)); 707 float adjustedPercent = (float) Math.max(dragPercent - .4, 0) * 5 / 3; 708 float extraOS = Math.abs(overscrollTop) - mTotalDragDistance; 709 float slingshotDist = mUsingCustomStart ? mSpinnerFinalOffset 710 - mOriginalOffsetTop : mSpinnerFinalOffset; 711 float tensionSlingshotPercent = Math.max(0, 712 Math.min(extraOS, slingshotDist * 2) / slingshotDist); 713 float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow( 714 (tensionSlingshotPercent / 4), 2)) * 2f; 715 float extraMove = (slingshotDist) * tensionPercent * 2; 716 717 int targetY = mOriginalOffsetTop 718 + (int) ((slingshotDist * dragPercent) + extraMove); 719 // where 1.0f is a full circle 720 if (mCircleView.getVisibility() != View.VISIBLE) { 721 mCircleView.setVisibility(View.VISIBLE); 722 } 723 if (!mScale) { 724 ViewCompat.setScaleX(mCircleView, 1f); 725 ViewCompat.setScaleY(mCircleView, 1f); 726 } 727 if (overscrollTop < mTotalDragDistance) { 728 if (mScale) { 729 setAnimationProgress(overscrollTop / mTotalDragDistance); 730 } 731 if (mProgress.getAlpha() > STARTING_PROGRESS_ALPHA 732 && !isAnimationRunning(mAlphaStartAnimation)) { 733 // Animate the alpha 734 startProgressAlphaStartAnimation(); 735 } 736 float strokeStart = (float) (adjustedPercent * .8f); 737 mProgress.setStartEndTrim(0f, Math.min(MAX_PROGRESS_ANGLE, strokeStart)); 738 mProgress.setArrowScale(Math.min(1f, adjustedPercent)); 739 } else { 740 if (mProgress.getAlpha() < MAX_ALPHA 741 && !isAnimationRunning(mAlphaMaxAnimation)) { 742 // Animate the alpha 743 startProgressAlphaMaxAnimation(); 744 } 745 } 746 float rotation = (-0.25f + .4f * adjustedPercent + tensionPercent * 2) * .5f; 747 mProgress.setProgressRotation(rotation); 748 setTargetOffsetTopAndBottom(targetY - mCurrentTargetOffsetTop, 749 true /* requires update */); 750 } 751 break; 752 } 753 case MotionEventCompat.ACTION_POINTER_DOWN: { 754 final int index = MotionEventCompat.getActionIndex(ev); 755 mActivePointerId = MotionEventCompat.getPointerId(ev, index); 756 break; 757 } 758 759 case MotionEventCompat.ACTION_POINTER_UP: 760 onSecondaryPointerUp(ev); 761 break; 762 763 case MotionEvent.ACTION_UP: 764 case MotionEvent.ACTION_CANCEL: { 765 if (mActivePointerId == INVALID_POINTER) { 766 if (action == MotionEvent.ACTION_UP) { 767 Log.e(LOG_TAG, "Got ACTION_UP event but don't have an active pointer id."); 768 } 769 return false; 770 } 771 final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); 772 final float y = MotionEventCompat.getY(ev, pointerIndex); 773 final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE; 774 mIsBeingDragged = false; 775 if (overscrollTop > mTotalDragDistance) { 776 setRefreshing(true, true /* notify */); 777 } else { 778 // cancel refresh 779 mRefreshing = false; 780 mProgress.setStartEndTrim(0f, 0f); 781 Animation.AnimationListener listener = null; 782 if (!mScale) { 783 listener = new Animation.AnimationListener() { 784 785 @Override 786 public void onAnimationStart(Animation animation) { 787 } 788 789 @Override 790 public void onAnimationEnd(Animation animation) { 791 if (!mScale) { 792 startScaleDownAnimation(null); 793 } 794 } 795 796 @Override 797 public void onAnimationRepeat(Animation animation) { 798 } 799 800 }; 801 } 802 animateOffsetToStartPosition(mCurrentTargetOffsetTop, listener); 803 mProgress.showArrow(false); 804 } 805 mActivePointerId = INVALID_POINTER; 806 return false; 807 } 808 } 809 810 return true; 811 } 812 813 private void animateOffsetToCorrectPosition(int from, AnimationListener listener) { 814 mFrom = from; 815 mAnimateToCorrectPosition.reset(); 816 mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION); 817 mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator); 818 if (listener != null) { 819 mCircleView.setAnimationListener(listener); 820 } 821 mCircleView.clearAnimation(); 822 mCircleView.startAnimation(mAnimateToCorrectPosition); 823 } 824 825 private void animateOffsetToStartPosition(int from, AnimationListener listener) { 826 if (mScale) { 827 // Scale the item back down 828 startScaleDownReturnToStartAnimation(from, listener); 829 } else { 830 mFrom = from; 831 mAnimateToStartPosition.reset(); 832 mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION); 833 mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator); 834 if (listener != null) { 835 mCircleView.setAnimationListener(listener); 836 } 837 mCircleView.clearAnimation(); 838 mCircleView.startAnimation(mAnimateToStartPosition); 839 } 840 } 841 842 private final Animation mAnimateToCorrectPosition = new Animation() { 843 @Override 844 public void applyTransformation(float interpolatedTime, Transformation t) { 845 int targetTop = 0; 846 int endTarget = 0; 847 if (!mUsingCustomStart) { 848 endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop)); 849 } else { 850 endTarget = (int) mSpinnerFinalOffset; 851 } 852 targetTop = (mFrom + (int) ((endTarget - mFrom) * interpolatedTime)); 853 int offset = targetTop - mCircleView.getTop(); 854 setTargetOffsetTopAndBottom(offset, false /* requires update */); 855 } 856 }; 857 858 private void moveToStart(float interpolatedTime) { 859 int targetTop = 0; 860 targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime)); 861 int offset = targetTop - mCircleView.getTop(); 862 setTargetOffsetTopAndBottom(offset, false /* requires update */); 863 } 864 865 private final Animation mAnimateToStartPosition = new Animation() { 866 @Override 867 public void applyTransformation(float interpolatedTime, Transformation t) { 868 moveToStart(interpolatedTime); 869 } 870 }; 871 872 private void startScaleDownReturnToStartAnimation(int from, 873 Animation.AnimationListener listener) { 874 mFrom = from; 875 if (isAlphaUsedForScale()) { 876 mStartingScale = mProgress.getAlpha(); 877 } else { 878 mStartingScale = ViewCompat.getScaleX(mCircleView); 879 } 880 mScaleDownToStartAnimation = new Animation() { 881 @Override 882 public void applyTransformation(float interpolatedTime, Transformation t) { 883 float targetScale = (mStartingScale + (-mStartingScale * interpolatedTime)); 884 setAnimationProgress(targetScale); 885 moveToStart(interpolatedTime); 886 } 887 }; 888 mScaleDownToStartAnimation.setDuration(SCALE_DOWN_DURATION); 889 if (listener != null) { 890 mCircleView.setAnimationListener(listener); 891 } 892 mCircleView.clearAnimation(); 893 mCircleView.startAnimation(mScaleDownToStartAnimation); 894 } 895 896 private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) { 897 mCircleView.bringToFront(); 898 mCircleView.offsetTopAndBottom(offset); 899 mCurrentTargetOffsetTop = mCircleView.getTop(); 900 if (requiresUpdate && android.os.Build.VERSION.SDK_INT < 11) { 901 invalidate(); 902 } 903 } 904 905 private void onSecondaryPointerUp(MotionEvent ev) { 906 final int pointerIndex = MotionEventCompat.getActionIndex(ev); 907 final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); 908 if (pointerId == mActivePointerId) { 909 // This was our active pointer going up. Choose a new 910 // active pointer and adjust accordingly. 911 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 912 mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); 913 } 914 } 915 916 /** 917 * Classes that wish to be notified when the swipe gesture correctly 918 * triggers a refresh should implement this interface. 919 */ 920 public interface OnRefreshListener { 921 public void onRefresh(); 922 } 923}