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