| 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.graphics.PointF; |
| 20 | import android.util.DisplayMetrics; |
| 21 | import android.view.View; |
| 22 | |
| 23 | import androidx.annotation.NonNull; |
| 24 | import androidx.annotation.Nullable; |
| 25 | |
| 26 | /** |
| 27 | * Implementation of the {@link SnapHelper} supporting pager style snapping in either vertical or |
| 28 | * horizontal orientation. |
| 29 | * |
| 30 | * <p> |
| 31 | * |
| 32 | * PagerSnapHelper can help achieve a similar behavior to |
| 33 | * {@link androidx.viewpager.widget.ViewPager}. Set both {@link RecyclerView} and the items of the |
| 34 | * {@link RecyclerView.Adapter} to have |
| 35 | * {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT} height and width and then attach |
| 36 | * PagerSnapHelper to the {@link RecyclerView} using {@link #attachToRecyclerView(RecyclerView)}. |
| 37 | */ |
| 38 | public class PagerSnapHelper extends SnapHelper { |
| 39 | private static final int MAX_SCROLL_ON_FLING_DURATION = 100; // ms |
| 40 | |
| 41 | // Orientation helpers are lazily created per LayoutManager. |
| 42 | @Nullable |
| 43 | private OrientationHelper mVerticalHelper; |
| 44 | @Nullable |
| 45 | private OrientationHelper mHorizontalHelper; |
| 46 | |
| 47 | @Nullable |
| 48 | @Override |
| 49 | public int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager, |
| 50 | @NonNull View targetView) { |
| 51 | int[] out = new int[2]; |
| 52 | if (layoutManager.canScrollHorizontally()) { |
| 53 | out[0] = distanceToCenter(layoutManager, targetView, |
| 54 | getHorizontalHelper(layoutManager)); |
| 55 | } else { |
| 56 | out[0] = 0; |
| 57 | } |
| 58 | |
| 59 | if (layoutManager.canScrollVertically()) { |
| 60 | out[1] = distanceToCenter(layoutManager, targetView, |
| 61 | getVerticalHelper(layoutManager)); |
| 62 | } else { |
| 63 | out[1] = 0; |
| 64 | } |
| 65 | return out; |
| 66 | } |
| 67 | |
| 68 | @Nullable |
| 69 | @Override |
| 70 | public View findSnapView(RecyclerView.LayoutManager layoutManager) { |
| 71 | if (layoutManager.canScrollVertically()) { |
| 72 | return findCenterView(layoutManager, getVerticalHelper(layoutManager)); |
| 73 | } else if (layoutManager.canScrollHorizontally()) { |
| 74 | return findCenterView(layoutManager, getHorizontalHelper(layoutManager)); |
| 75 | } |
| 76 | return null; |
| 77 | } |
| 78 | |
| 79 | @Override |
| 80 | public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, |
| 81 | int velocityY) { |
| 82 | final int itemCount = layoutManager.getItemCount(); |
| 83 | if (itemCount == 0) { |
| 84 | return RecyclerView.NO_POSITION; |
| 85 | } |
| 86 | |
| 87 | final OrientationHelper orientationHelper = getOrientationHelper(layoutManager); |
| 88 | if (orientationHelper == null) { |
| 89 | return RecyclerView.NO_POSITION; |
| 90 | } |
| 91 | |
| 92 | // A child that is exactly in the center is eligible for both before and after |
| 93 | View closestChildBeforeCenter = null; |
| 94 | int distanceBefore = Integer.MIN_VALUE; |
| 95 | View closestChildAfterCenter = null; |
| 96 | int distanceAfter = Integer.MAX_VALUE; |
| 97 | |
| 98 | // Find the first view before the center, and the first view after the center |
| 99 | final int childCount = layoutManager.getChildCount(); |
| 100 | for (int i = 0; i < childCount; i++) { |
| 101 | final View child = layoutManager.getChildAt(i); |
| 102 | if (child == null) { |
| 103 | continue; |
| 104 | } |
| 105 | final int distance = distanceToCenter(layoutManager, child, orientationHelper); |
| 106 | |
| 107 | if (distance <= 0 && distance > distanceBefore) { |
| 108 | // Child is before the center and closer then the previous best |
| 109 | distanceBefore = distance; |
| 110 | closestChildBeforeCenter = child; |
| 111 | } |
| 112 | if (distance >= 0 && distance < distanceAfter) { |
| 113 | // Child is after the center and closer then the previous best |
| 114 | distanceAfter = distance; |
| 115 | closestChildAfterCenter = child; |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | // Return the position of the first child from the center, in the direction of the fling |
| 120 | final boolean forwardDirection = isForwardFling(layoutManager, velocityX, velocityY); |
| 121 | if (forwardDirection && closestChildAfterCenter != null) { |
| 122 | return layoutManager.getPosition(closestChildAfterCenter); |
| 123 | } else if (!forwardDirection && closestChildBeforeCenter != null) { |
| 124 | return layoutManager.getPosition(closestChildBeforeCenter); |
| 125 | } |
| 126 | |
| 127 | // There is no child in the direction of the fling. Either it doesn't exist (start/end of |
| 128 | // the list), or it is not yet attached (very rare case when children are larger then the |
| 129 | // viewport). Extrapolate from the child that is visible to get the position of the view to |
| 130 | // snap to. |
| 131 | View visibleView = forwardDirection ? closestChildBeforeCenter : closestChildAfterCenter; |
| 132 | if (visibleView == null) { |
| 133 | return RecyclerView.NO_POSITION; |
| 134 | } |
| 135 | int visiblePosition = layoutManager.getPosition(visibleView); |
| 136 | int snapToPosition = visiblePosition |
| 137 | + (isReverseLayout(layoutManager) == forwardDirection ? -1 : +1); |
| 138 | |
| 139 | if (snapToPosition < 0 || snapToPosition >= itemCount) { |
| 140 | return RecyclerView.NO_POSITION; |
| 141 | } |
| 142 | return snapToPosition; |
| 143 | } |
| 144 | |
| 145 | private boolean isForwardFling(RecyclerView.LayoutManager layoutManager, int velocityX, |
| 146 | int velocityY) { |
| 147 | if (layoutManager.canScrollHorizontally()) { |
| 148 | return velocityX > 0; |
| 149 | } else { |
| 150 | return velocityY > 0; |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | private boolean isReverseLayout(RecyclerView.LayoutManager layoutManager) { |
| 155 | final int itemCount = layoutManager.getItemCount(); |
| 156 | if ((layoutManager instanceof RecyclerView.SmoothScroller.ScrollVectorProvider)) { |
| 157 | RecyclerView.SmoothScroller.ScrollVectorProvider vectorProvider = |
| 158 | (RecyclerView.SmoothScroller.ScrollVectorProvider) layoutManager; |
| 159 | PointF vectorForEnd = vectorProvider.computeScrollVectorForPosition(itemCount - 1); |
| 160 | if (vectorForEnd != null) { |
| 161 | return vectorForEnd.x < 0 || vectorForEnd.y < 0; |
| 162 | } |
| 163 | } |
| 164 | return false; |
| 165 | } |
| 166 | |
| 167 | @Override |
| 168 | protected LinearSmoothScroller createSnapScroller(RecyclerView.LayoutManager layoutManager) { |
| 169 | if (!(layoutManager instanceof RecyclerView.SmoothScroller.ScrollVectorProvider)) { |
| 170 | return null; |
| 171 | } |
| 172 | return new LinearSmoothScroller(mRecyclerView.getContext()) { |
| 173 | @Override |
| 174 | protected void onTargetFound(View targetView, RecyclerView.State state, Action action) { |
| 175 | int[] snapDistances = calculateDistanceToFinalSnap(mRecyclerView.getLayoutManager(), |
| 176 | targetView); |
| 177 | final int dx = snapDistances[0]; |
| 178 | final int dy = snapDistances[1]; |
| 179 | final int time = calculateTimeForDeceleration(Math.max(Math.abs(dx), Math.abs(dy))); |
| 180 | if (time > 0) { |
| 181 | action.update(dx, dy, time, mDecelerateInterpolator); |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | @Override |
| 186 | protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) { |
| 187 | return MILLISECONDS_PER_INCH / displayMetrics.densityDpi; |
| 188 | } |
| 189 | |
| 190 | @Override |
| 191 | protected int calculateTimeForScrolling(int dx) { |
| 192 | return Math.min(MAX_SCROLL_ON_FLING_DURATION, super.calculateTimeForScrolling(dx)); |
| 193 | } |
| 194 | }; |
| 195 | } |
| 196 | |
| 197 | private int distanceToCenter(@NonNull RecyclerView.LayoutManager layoutManager, |
| 198 | @NonNull View targetView, OrientationHelper helper) { |
| 199 | final int childCenter = helper.getDecoratedStart(targetView) |
| 200 | + (helper.getDecoratedMeasurement(targetView) / 2); |
| 201 | final int containerCenter; |
| 202 | if (layoutManager.getClipToPadding()) { |
| 203 | containerCenter = helper.getStartAfterPadding() + helper.getTotalSpace() / 2; |
| 204 | } else { |
| 205 | containerCenter = helper.getEnd() / 2; |
| 206 | } |
| 207 | return childCenter - containerCenter; |
| 208 | } |
| 209 | |
| 210 | /** |
| 211 | * Return the child view that is currently closest to the center of this parent. |
| 212 | * |
| 213 | * @param layoutManager The {@link RecyclerView.LayoutManager} associated with the attached |
| 214 | * {@link RecyclerView}. |
| 215 | * @param helper The relevant {@link OrientationHelper} for the attached {@link RecyclerView}. |
| 216 | * |
| 217 | * @return the child view that is currently closest to the center of this parent. |
| 218 | */ |
| 219 | @Nullable |
| 220 | private View findCenterView(RecyclerView.LayoutManager layoutManager, |
| 221 | OrientationHelper helper) { |
| 222 | int childCount = layoutManager.getChildCount(); |
| 223 | if (childCount == 0) { |
| 224 | return null; |
| 225 | } |
| 226 | |
| 227 | View closestChild = null; |
| 228 | final int center; |
| 229 | if (layoutManager.getClipToPadding()) { |
| 230 | center = helper.getStartAfterPadding() + helper.getTotalSpace() / 2; |
| 231 | } else { |
| 232 | center = helper.getEnd() / 2; |
| 233 | } |
| 234 | int absClosest = Integer.MAX_VALUE; |
| 235 | |
| 236 | for (int i = 0; i < childCount; i++) { |
| 237 | final View child = layoutManager.getChildAt(i); |
| 238 | int childCenter = helper.getDecoratedStart(child) |
| 239 | + (helper.getDecoratedMeasurement(child) / 2); |
| 240 | int absDistance = Math.abs(childCenter - center); |
| 241 | |
| 242 | /* if child center is closer than previous closest, set it as closest */ |
| 243 | if (absDistance < absClosest) { |
| 244 | absClosest = absDistance; |
| 245 | closestChild = child; |
| 246 | } |
| 247 | } |
| 248 | return closestChild; |
| 249 | } |
| 250 | |
| 251 | @Nullable |
| 252 | private OrientationHelper getOrientationHelper(RecyclerView.LayoutManager layoutManager) { |
| 253 | if (layoutManager.canScrollVertically()) { |
| 254 | return getVerticalHelper(layoutManager); |
| 255 | } else if (layoutManager.canScrollHorizontally()) { |
| 256 | return getHorizontalHelper(layoutManager); |
| 257 | } else { |
| 258 | return null; |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | @NonNull |
| 263 | private OrientationHelper getVerticalHelper(@NonNull RecyclerView.LayoutManager layoutManager) { |
| 264 | if (mVerticalHelper == null || mVerticalHelper.mLayoutManager != layoutManager) { |
| 265 | mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager); |
| 266 | } |
| 267 | return mVerticalHelper; |
| 268 | } |
| 269 | |
| 270 | @NonNull |
| 271 | private OrientationHelper getHorizontalHelper( |
| 272 | @NonNull RecyclerView.LayoutManager layoutManager) { |
| 273 | if (mHorizontalHelper == null || mHorizontalHelper.mLayoutManager != layoutManager) { |
| 274 | mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager); |
| 275 | } |
| 276 | return mHorizontalHelper; |
| 277 | } |
| 278 | } |
| 279 | |