| 1 | /* |
| 2 | * Copyright 2018 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 | |
| 17 | package androidx.recyclerview.widget; |
| 18 | |
| 19 | import android.content.Context; |
| 20 | import android.graphics.PointF; |
| 21 | import android.util.DisplayMetrics; |
| 22 | import android.view.View; |
| 23 | import android.view.animation.DecelerateInterpolator; |
| 24 | import android.view.animation.LinearInterpolator; |
| 25 | |
| 26 | /** |
| 27 | * {@link RecyclerView.SmoothScroller} implementation which uses a {@link LinearInterpolator} until |
| 28 | * the target position becomes a child of the RecyclerView and then uses a |
| 29 | * {@link DecelerateInterpolator} to slowly approach to target position. |
| 30 | * <p> |
| 31 | * If the {@link RecyclerView.LayoutManager} you are using does not implement the |
| 32 | * {@link RecyclerView.SmoothScroller.ScrollVectorProvider} interface, then you must override the |
| 33 | * {@link #computeScrollVectorForPosition(int)} method. All the LayoutManagers bundled with |
| 34 | * the support library implement this interface. |
| 35 | */ |
| 36 | public class LinearSmoothScroller extends RecyclerView.SmoothScroller { |
| 37 | |
| 38 | private static final boolean DEBUG = false; |
| 39 | |
| 40 | private static final float MILLISECONDS_PER_INCH = 25f; |
| 41 | |
| 42 | private static final int TARGET_SEEK_SCROLL_DISTANCE_PX = 10000; |
| 43 | |
| 44 | /** |
| 45 | * Align child view's left or top with parent view's left or top |
| 46 | * |
| 47 | * @see #calculateDtToFit(int, int, int, int, int) |
| 48 | * @see #calculateDxToMakeVisible(android.view.View, int) |
| 49 | * @see #calculateDyToMakeVisible(android.view.View, int) |
| 50 | */ |
| 51 | public static final int SNAP_TO_START = -1; |
| 52 | |
| 53 | /** |
| 54 | * Align child view's right or bottom with parent view's right or bottom |
| 55 | * |
| 56 | * @see #calculateDtToFit(int, int, int, int, int) |
| 57 | * @see #calculateDxToMakeVisible(android.view.View, int) |
| 58 | * @see #calculateDyToMakeVisible(android.view.View, int) |
| 59 | */ |
| 60 | public static final int SNAP_TO_END = 1; |
| 61 | |
| 62 | /** |
| 63 | * <p>Decides if the child should be snapped from start or end, depending on where it |
| 64 | * currently is in relation to its parent.</p> |
| 65 | * <p>For instance, if the view is virtually on the left of RecyclerView, using |
| 66 | * {@code SNAP_TO_ANY} is the same as using {@code SNAP_TO_START}</p> |
| 67 | * |
| 68 | * @see #calculateDtToFit(int, int, int, int, int) |
| 69 | * @see #calculateDxToMakeVisible(android.view.View, int) |
| 70 | * @see #calculateDyToMakeVisible(android.view.View, int) |
| 71 | */ |
| 72 | public static final int SNAP_TO_ANY = 0; |
| 73 | |
| 74 | // Trigger a scroll to a further distance than TARGET_SEEK_SCROLL_DISTANCE_PX so that if target |
| 75 | // view is not laid out until interim target position is reached, we can detect the case before |
| 76 | // scrolling slows down and reschedule another interim target scroll |
| 77 | private static final float TARGET_SEEK_EXTRA_SCROLL_RATIO = 1.2f; |
| 78 | |
| 79 | protected final LinearInterpolator mLinearInterpolator = new LinearInterpolator(); |
| 80 | |
| 81 | protected final DecelerateInterpolator mDecelerateInterpolator = new DecelerateInterpolator(); |
| 82 | |
| 83 | protected PointF mTargetVector; |
| 84 | |
| 85 | private final DisplayMetrics mDisplayMetrics; |
| 86 | private boolean mHasCalculatedMillisPerPixel = false; |
| 87 | private float mMillisPerPixel; |
| 88 | |
| 89 | // Temporary variables to keep track of the interim scroll target. These values do not |
| 90 | // point to a real item position, rather point to an estimated location pixels. |
| 91 | protected int mInterimTargetDx = 0, mInterimTargetDy = 0; |
| 92 | |
| 93 | public LinearSmoothScroller(Context context) { |
| 94 | mDisplayMetrics = context.getResources().getDisplayMetrics(); |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * {@inheritDoc} |
| 99 | */ |
| 100 | @Override |
| 101 | protected void onStart() { |
| 102 | |
| 103 | } |
| 104 | |
| 105 | /** |
| 106 | * {@inheritDoc} |
| 107 | */ |
| 108 | @Override |
| 109 | protected void onTargetFound(View targetView, RecyclerView.State state, Action action) { |
| 110 | final int dx = calculateDxToMakeVisible(targetView, getHorizontalSnapPreference()); |
| 111 | final int dy = calculateDyToMakeVisible(targetView, getVerticalSnapPreference()); |
| 112 | final int distance = (int) Math.sqrt(dx * dx + dy * dy); |
| 113 | final int time = calculateTimeForDeceleration(distance); |
| 114 | if (time > 0) { |
| 115 | action.update(-dx, -dy, time, mDecelerateInterpolator); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /** |
| 120 | * {@inheritDoc} |
| 121 | */ |
| 122 | @Override |
| 123 | protected void onSeekTargetStep(int dx, int dy, RecyclerView.State state, Action action) { |
| 124 | // TODO(b/72745539): Is there ever a time when onSeekTargetStep should be called when |
| 125 | // getChildCount returns 0? Should this logic be extracted out of this method such that |
| 126 | // this method is not called if getChildCount() returns 0? |
| 127 | if (getChildCount() == 0) { |
| 128 | stop(); |
| 129 | return; |
| 130 | } |
| 131 | //noinspection PointlessBooleanExpression |
| 132 | if (DEBUG && mTargetVector != null |
| 133 | && ((mTargetVector.x * dx < 0 || mTargetVector.y * dy < 0))) { |
| 134 | throw new IllegalStateException("Scroll happened in the opposite direction" |
| 135 | + " of the target. Some calculations are wrong"); |
| 136 | } |
| 137 | mInterimTargetDx = clampApplyScroll(mInterimTargetDx, dx); |
| 138 | mInterimTargetDy = clampApplyScroll(mInterimTargetDy, dy); |
| 139 | |
| 140 | if (mInterimTargetDx == 0 && mInterimTargetDy == 0) { |
| 141 | updateActionForInterimTarget(action); |
| 142 | } // everything is valid, keep going |
| 143 | |
| 144 | } |
| 145 | |
| 146 | /** |
| 147 | * {@inheritDoc} |
| 148 | */ |
| 149 | @Override |
| 150 | protected void onStop() { |
| 151 | mInterimTargetDx = mInterimTargetDy = 0; |
| 152 | mTargetVector = null; |
| 153 | } |
| 154 | |
| 155 | /** |
| 156 | * Calculates the scroll speed. |
| 157 | * |
| 158 | * <p>By default, LinearSmoothScroller assumes this method always returns the same value and |
| 159 | * caches the result of calling it. |
| 160 | * |
| 161 | * @param displayMetrics DisplayMetrics to be used for real dimension calculations |
| 162 | * @return The time (in ms) it should take for each pixel. For instance, if returned value is |
| 163 | * 2 ms, it means scrolling 1000 pixels with LinearInterpolation should take 2 seconds. |
| 164 | */ |
| 165 | protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) { |
| 166 | return MILLISECONDS_PER_INCH / displayMetrics.densityDpi; |
| 167 | } |
| 168 | |
| 169 | private float getSpeedPerPixel() { |
| 170 | if (!mHasCalculatedMillisPerPixel) { |
| 171 | mMillisPerPixel = calculateSpeedPerPixel(mDisplayMetrics); |
| 172 | mHasCalculatedMillisPerPixel = true; |
| 173 | } |
| 174 | return mMillisPerPixel; |
| 175 | } |
| 176 | |
| 177 | /** |
| 178 | * <p>Calculates the time for deceleration so that transition from LinearInterpolator to |
| 179 | * DecelerateInterpolator looks smooth.</p> |
| 180 | * |
| 181 | * @param dx Distance to scroll |
| 182 | * @return Time for DecelerateInterpolator to smoothly traverse the distance when transitioning |
| 183 | * from LinearInterpolation |
| 184 | */ |
| 185 | protected int calculateTimeForDeceleration(int dx) { |
| 186 | // we want to cover same area with the linear interpolator for the first 10% of the |
| 187 | // interpolation. After that, deceleration will take control. |
| 188 | // area under curve (1-(1-x)^2) can be calculated as (1 - x/3) * x * x |
| 189 | // which gives 0.100028 when x = .3356 |
| 190 | // this is why we divide linear scrolling time with .3356 |
| 191 | return (int) Math.ceil(calculateTimeForScrolling(dx) / .3356); |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * Calculates the time it should take to scroll the given distance (in pixels) |
| 196 | * |
| 197 | * @param dx Distance in pixels that we want to scroll |
| 198 | * @return Time in milliseconds |
| 199 | * @see #calculateSpeedPerPixel(android.util.DisplayMetrics) |
| 200 | */ |
| 201 | protected int calculateTimeForScrolling(int dx) { |
| 202 | // In a case where dx is very small, rounding may return 0 although dx > 0. |
| 203 | // To avoid that issue, ceil the result so that if dx > 0, we'll always return positive |
| 204 | // time. |
| 205 | return (int) Math.ceil(Math.abs(dx) * getSpeedPerPixel()); |
| 206 | } |
| 207 | |
| 208 | /** |
| 209 | * When scrolling towards a child view, this method defines whether we should align the left |
| 210 | * or the right edge of the child with the parent RecyclerView. |
| 211 | * |
| 212 | * @return SNAP_TO_START, SNAP_TO_END or SNAP_TO_ANY; depending on the current target vector |
| 213 | * @see #SNAP_TO_START |
| 214 | * @see #SNAP_TO_END |
| 215 | * @see #SNAP_TO_ANY |
| 216 | */ |
| 217 | protected int getHorizontalSnapPreference() { |
| 218 | return mTargetVector == null || mTargetVector.x == 0 ? SNAP_TO_ANY : |
| 219 | mTargetVector.x > 0 ? SNAP_TO_END : SNAP_TO_START; |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * When scrolling towards a child view, this method defines whether we should align the top |
| 224 | * or the bottom edge of the child with the parent RecyclerView. |
| 225 | * |
| 226 | * @return SNAP_TO_START, SNAP_TO_END or SNAP_TO_ANY; depending on the current target vector |
| 227 | * @see #SNAP_TO_START |
| 228 | * @see #SNAP_TO_END |
| 229 | * @see #SNAP_TO_ANY |
| 230 | */ |
| 231 | protected int getVerticalSnapPreference() { |
| 232 | return mTargetVector == null || mTargetVector.y == 0 ? SNAP_TO_ANY : |
| 233 | mTargetVector.y > 0 ? SNAP_TO_END : SNAP_TO_START; |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * When the target scroll position is not a child of the RecyclerView, this method calculates |
| 238 | * a direction vector towards that child and triggers a smooth scroll. |
| 239 | * |
| 240 | * @see #computeScrollVectorForPosition(int) |
| 241 | */ |
| 242 | protected void updateActionForInterimTarget(Action action) { |
| 243 | // find an interim target position |
| 244 | PointF scrollVector = computeScrollVectorForPosition(getTargetPosition()); |
| 245 | if (scrollVector == null || (scrollVector.x == 0 && scrollVector.y == 0)) { |
| 246 | final int target = getTargetPosition(); |
| 247 | action.jumpTo(target); |
| 248 | stop(); |
| 249 | return; |
| 250 | } |
| 251 | normalize(scrollVector); |
| 252 | mTargetVector = scrollVector; |
| 253 | |
| 254 | mInterimTargetDx = (int) (TARGET_SEEK_SCROLL_DISTANCE_PX * scrollVector.x); |
| 255 | mInterimTargetDy = (int) (TARGET_SEEK_SCROLL_DISTANCE_PX * scrollVector.y); |
| 256 | final int time = calculateTimeForScrolling(TARGET_SEEK_SCROLL_DISTANCE_PX); |
| 257 | // To avoid UI hiccups, trigger a smooth scroll to a distance little further than the |
| 258 | // interim target. Since we track the distance travelled in onSeekTargetStep callback, it |
| 259 | // won't actually scroll more than what we need. |
| 260 | action.update((int) (mInterimTargetDx * TARGET_SEEK_EXTRA_SCROLL_RATIO), |
| 261 | (int) (mInterimTargetDy * TARGET_SEEK_EXTRA_SCROLL_RATIO), |
| 262 | (int) (time * TARGET_SEEK_EXTRA_SCROLL_RATIO), mLinearInterpolator); |
| 263 | } |
| 264 | |
| 265 | private int clampApplyScroll(int tmpDt, int dt) { |
| 266 | final int before = tmpDt; |
| 267 | tmpDt -= dt; |
| 268 | if (before * tmpDt <= 0) { // changed sign, reached 0 or was 0, reset |
| 269 | return 0; |
| 270 | } |
| 271 | return tmpDt; |
| 272 | } |
| 273 | |
| 274 | /** |
| 275 | * Helper method for {@link #calculateDxToMakeVisible(android.view.View, int)} and |
| 276 | * {@link #calculateDyToMakeVisible(android.view.View, int)} |
| 277 | */ |
| 278 | public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int |
| 279 | snapPreference) { |
| 280 | switch (snapPreference) { |
| 281 | case SNAP_TO_START: |
| 282 | return boxStart - viewStart; |
| 283 | case SNAP_TO_END: |
| 284 | return boxEnd - viewEnd; |
| 285 | case SNAP_TO_ANY: |
| 286 | final int dtStart = boxStart - viewStart; |
| 287 | if (dtStart > 0) { |
| 288 | return dtStart; |
| 289 | } |
| 290 | final int dtEnd = boxEnd - viewEnd; |
| 291 | if (dtEnd < 0) { |
| 292 | return dtEnd; |
| 293 | } |
| 294 | break; |
| 295 | default: |
| 296 | throw new IllegalArgumentException("snap preference should be one of the" |
| 297 | + " constants defined in SmoothScroller, starting with SNAP_"); |
| 298 | } |
| 299 | return 0; |
| 300 | } |
| 301 | |
| 302 | /** |
| 303 | * Calculates the vertical scroll amount necessary to make the given view fully visible |
| 304 | * inside the RecyclerView. |
| 305 | * |
| 306 | * @param view The view which we want to make fully visible |
| 307 | * @param snapPreference The edge which the view should snap to when entering the visible |
| 308 | * area. One of {@link #SNAP_TO_START}, {@link #SNAP_TO_END} or |
| 309 | * {@link #SNAP_TO_ANY}. |
| 310 | * @return The vertical scroll amount necessary to make the view visible with the given |
| 311 | * snap preference. |
| 312 | */ |
| 313 | public int calculateDyToMakeVisible(View view, int snapPreference) { |
| 314 | final RecyclerView.LayoutManager layoutManager = getLayoutManager(); |
| 315 | if (layoutManager == null || !layoutManager.canScrollVertically()) { |
| 316 | return 0; |
| 317 | } |
| 318 | final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) |
| 319 | view.getLayoutParams(); |
| 320 | final int top = layoutManager.getDecoratedTop(view) - params.topMargin; |
| 321 | final int bottom = layoutManager.getDecoratedBottom(view) + params.bottomMargin; |
| 322 | final int start = layoutManager.getPaddingTop(); |
| 323 | final int end = layoutManager.getHeight() - layoutManager.getPaddingBottom(); |
| 324 | return calculateDtToFit(top, bottom, start, end, snapPreference); |
| 325 | } |
| 326 | |
| 327 | /** |
| 328 | * Calculates the horizontal scroll amount necessary to make the given view fully visible |
| 329 | * inside the RecyclerView. |
| 330 | * |
| 331 | * @param view The view which we want to make fully visible |
| 332 | * @param snapPreference The edge which the view should snap to when entering the visible |
| 333 | * area. One of {@link #SNAP_TO_START}, {@link #SNAP_TO_END} or |
| 334 | * {@link #SNAP_TO_END} |
| 335 | * @return The vertical scroll amount necessary to make the view visible with the given |
| 336 | * snap preference. |
| 337 | */ |
| 338 | public int calculateDxToMakeVisible(View view, int snapPreference) { |
| 339 | final RecyclerView.LayoutManager layoutManager = getLayoutManager(); |
| 340 | if (layoutManager == null || !layoutManager.canScrollHorizontally()) { |
| 341 | return 0; |
| 342 | } |
| 343 | final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) |
| 344 | view.getLayoutParams(); |
| 345 | final int left = layoutManager.getDecoratedLeft(view) - params.leftMargin; |
| 346 | final int right = layoutManager.getDecoratedRight(view) + params.rightMargin; |
| 347 | final int start = layoutManager.getPaddingLeft(); |
| 348 | final int end = layoutManager.getWidth() - layoutManager.getPaddingRight(); |
| 349 | return calculateDtToFit(left, right, start, end, snapPreference); |
| 350 | } |
| 351 | } |
| 352 | |