blob: c0c65eaaeefd87ea5c6825878177289b622dc88e [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
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
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen7d30a372013-07-01 17:03:59 -070027import android.content.res.Resources;
Adam Cohen9c4949e2010-10-05 12:27:22 -070028import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070029import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070030import android.graphics.Matrix;
31import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070032import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070033import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070034import android.os.Parcel;
35import android.os.Parcelable;
36import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070037import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070038import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080039import android.view.InputDevice;
40import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070041import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewGroup;
46import android.view.ViewParent;
Adam Cohen96d30a12013-07-16 18:13:21 -070047import android.view.ViewGroup.LayoutParams;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070049import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070050import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070051import android.view.animation.AnimationUtils;
52import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080053import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070054import android.view.animation.LinearInterpolator;
Adam Cohen96d30a12013-07-16 18:13:21 -070055import android.widget.FrameLayout;
Winson Chung321e9ee2010-08-09 13:37:56 -070056import android.widget.Scroller;
57
Winson Chung6a0f57d2011-06-29 20:10:49 -070058import java.util.ArrayList;
59
Winson Chung321e9ee2010-08-09 13:37:56 -070060/**
61 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070062 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070063 */
Michael Jurka8b805b12012-04-18 14:23:14 -070064public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070065 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070066 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070067 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070068
Winson Chung86f77532010-08-24 11:08:22 -070069 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070070 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070071
Adam Cohen7d30a372013-07-01 17:03:59 -070072 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070073 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070074 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070075
Adam Cohenb5ba0972011-09-07 18:02:31 -070076 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070077 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080078
Adam Cohenb64cb5a2011-02-15 13:53:42 -080079 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080080 // The page is moved more than halfway, automatically move to the next page on touch up.
81 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080082
Adam Cohen265b9a62011-12-07 14:37:18 -080083 // The following constants need to be scaled based on density. The scaled versions will be
84 // assigned to the corresponding member variables below.
85 private static final int FLING_THRESHOLD_VELOCITY = 500;
86 private static final int MIN_SNAP_VELOCITY = 1500;
87 private static final int MIN_FLING_VELOCITY = 250;
88
Adam Cohen7d30a372013-07-01 17:03:59 -070089 // We are disabling touch interaction of the widget region for factory ROM.
90 private static final boolean DISABLE_TOUCH_INTERACTION = false;
91 private static final boolean DISABLE_TOUCH_SIDE_PAGES = false;
Adam Cohendedbd962013-07-11 14:21:49 -070092 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070093
Winson Chung8aad6102012-05-11 16:27:49 -070094 static final int AUTOMATIC_PAGE_SPACING = -1;
95
Adam Cohen265b9a62011-12-07 14:37:18 -080096 protected int mFlingThresholdVelocity;
97 protected int mMinFlingVelocity;
98 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -070099
Adam Cohenb5ba0972011-09-07 18:02:31 -0700100 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700101 protected float mSmoothingTime;
102 protected float mTouchX;
103
104 protected boolean mFirstLayout = true;
105
106 protected int mCurrentPage;
Adam Cohene61a9a22013-06-11 15:45:31 -0700107 protected int mChildCountOnLastMeasure;
108
Michael Jurka0142d492010-08-25 17:46:15 -0700109 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800110 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700111 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700112 private VelocityTracker mVelocityTracker;
113
Adam Cohen7d30a372013-07-01 17:03:59 -0700114 private float mParentDownMotionX;
115 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700116 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700117 private float mDownMotionY;
118 private float mDownScrollX;
Michael Jurka7426c422010-11-11 15:23:47 -0800119 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800120 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800121 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800122 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700123 private int mLastScreenCenter = -1;
Adam Cohen73894962011-10-31 13:17:17 -0700124 private int[] mChildOffsets;
125 private int[] mChildRelativeOffsets;
Winson Chung321e9ee2010-08-09 13:37:56 -0700126
Michael Jurka0142d492010-08-25 17:46:15 -0700127 protected final static int TOUCH_STATE_REST = 0;
128 protected final static int TOUCH_STATE_SCROLLING = 1;
129 protected final static int TOUCH_STATE_PREV_PAGE = 2;
130 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700131 protected final static int TOUCH_STATE_REORDERING = 4;
132
Adam Cohene45440e2010-10-14 18:33:38 -0700133 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700134
Michael Jurka0142d492010-08-25 17:46:15 -0700135 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700136 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700137
Michael Jurka0142d492010-08-25 17:46:15 -0700138 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700139
Michael Jurka7426c422010-11-11 15:23:47 -0800140 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700141 private int mPagingTouchSlop;
142 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700143 protected int mPageSpacing;
144 protected int mPageLayoutPaddingTop;
145 protected int mPageLayoutPaddingBottom;
146 protected int mPageLayoutPaddingLeft;
147 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700148 protected int mPageLayoutWidthGap;
149 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700150 protected int mCellCountX = 0;
151 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700152 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800153 protected boolean mAllowOverScroll = true;
154 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800155 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700156 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700157
Michael Jurka8b805b12012-04-18 14:23:14 -0700158 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800159 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
160 // the screens from continuing to translate beyond the normal bounds.
161 protected int mOverScrollX;
162
Michael Jurka5f1c5092010-09-03 14:15:02 -0700163 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700164
Michael Jurka5f1c5092010-09-03 14:15:02 -0700165 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700166
Winson Chung86f77532010-08-24 11:08:22 -0700167 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700168
Michael Jurkae326f182011-11-21 14:05:46 -0800169 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700170
Michael Jurka0142d492010-08-25 17:46:15 -0700171 // If true, syncPages and syncPageItems will be called to refresh pages
172 protected boolean mContentIsRefreshable = true;
173
174 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700175 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700176
177 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
178 // to switch to a new page
179 protected boolean mUsePagingTouchSlop = true;
180
Michael Jurka8b805b12012-04-18 14:23:14 -0700181 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700182 // (SmoothPagedView does this)
183 protected boolean mDeferScrollUpdate = false;
184
Patrick Dubroy1262e362010-10-06 15:49:50 -0700185 protected boolean mIsPageMoving = false;
186
Winson Chungf0ea4d32011-06-06 14:27:16 -0700187 // All syncs and layout passes are deferred until data is ready.
188 protected boolean mIsDataReady = false;
189
Adam Cohen7d30a372013-07-01 17:03:59 -0700190 protected boolean mAllowLongPress = true;
191
Winson Chungd2be3812013-07-16 11:11:32 -0700192 // Page Indicator
193 private int mPageIndicatorViewId;
194 private PageIndicator mPageIndicator;
Winson Chung007c6982011-06-14 13:27:53 -0700195
Adam Cohen7d30a372013-07-01 17:03:59 -0700196 // The viewport whether the pages are to be contained (the actual view may be larger than the
197 // viewport)
198 private Rect mViewport = new Rect();
199
200 // Reordering
201 // We use the min scale to determine how much to expand the actually PagedView measured
202 // dimensions such that when we are zoomed out, the view is not clipped
203 private int REORDERING_DROP_REPOSITION_DURATION = 200;
204 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
205 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
206 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 300;
207 private float REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE = 0.1f;
208 private long REORDERING_DELETE_DROP_TARGET_FADE_DURATION = 150;
209 private float mMinScale = 1f;
210 protected View mDragView;
211 protected AnimatorSet mZoomInOutAnim;
212 private Runnable mSidePageHoverRunnable;
213 private int mSidePageHoverIndex = -1;
214 // This variable's scope is only for the duration of startReordering() and endReordering()
215 private boolean mReorderingStarted = false;
216 // This variable's scope is for the duration of startReordering() and after the zoomIn()
217 // animation after endReordering()
218 private boolean mIsReordering;
219 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
220 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
221 private int mPostReorderingPreZoomInRemainingAnimationCount;
222 private Runnable mPostReorderingPreZoomInRunnable;
223
224 // Edge swiping
225 private boolean mOnlyAllowEdgeSwipes = false;
226 private boolean mDownEventOnEdge = false;
227 private int mEdgeSwipeRegionSize = 0;
228
229 // Convenience/caching
230 private Matrix mTmpInvMatrix = new Matrix();
231 private float[] mTmpPoint = new float[2];
232 private Rect mTmpRect = new Rect();
233 private Rect mAltTmpRect = new Rect();
234
235 // Fling to delete
236 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
237 private float FLING_TO_DELETE_FRICTION = 0.035f;
238 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
239 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
240 protected int mFlingToDeleteThresholdVelocity = -1400;
241 // Drag to delete
242 private boolean mDeferringForDelete = false;
243 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
244 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
245
246 // Drop to delete
247 private View mDeleteDropTarget;
248
249 private boolean mAutoComputePageSpacing = false;
250 private boolean mRecomputePageSpacing = false;
251
252 // Bouncer
253 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700254
Winson Chung86f77532010-08-24 11:08:22 -0700255 public interface PageSwitchListener {
256 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700257 }
258
Winson Chung321e9ee2010-08-09 13:37:56 -0700259 public PagedView(Context context) {
260 this(context, null);
261 }
262
263 public PagedView(Context context, AttributeSet attrs) {
264 this(context, attrs, 0);
265 }
266
267 public PagedView(Context context, AttributeSet attrs, int defStyle) {
268 super(context, attrs, defStyle);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700269 TypedArray a = context.obtainStyledAttributes(attrs,
270 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800271 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700272 if (mPageSpacing < 0) {
273 mAutoComputePageSpacing = mRecomputePageSpacing = true;
274 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700275 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800276 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700277 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800278 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700279 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800280 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700281 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800282 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700283 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700284 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700285 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700286 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700287 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700288 a.recycle();
289
Winson Chung321e9ee2010-08-09 13:37:56 -0700290 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700291 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700292 }
293
294 /**
295 * Initializes various states for this workspace.
296 */
Michael Jurka0142d492010-08-25 17:46:15 -0700297 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700298 mDirtyPageContent = new ArrayList<Boolean>();
299 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800300 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700301 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700302 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700303
304 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700305 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700306 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
307 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700308 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800309
Adam Cohen7d30a372013-07-01 17:03:59 -0700310 // Scale the fling-to-delete threshold by the density
311 mFlingToDeleteThresholdVelocity =
312 (int) (mFlingToDeleteThresholdVelocity * mDensity);
313
Adam Cohen265b9a62011-12-07 14:37:18 -0800314 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
315 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
316 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700317 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700318 }
319
Winson Chungd2be3812013-07-16 11:11:32 -0700320 protected void onAttachedToWindow() {
321 // Hook up the page indicator
322 ViewGroup parent = (ViewGroup) getParent();
323 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
324 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
325 mPageIndicator.removeAllMarkers();
326 mPageIndicator.addMarkers(getChildCount());
327 }
328 }
329
330 protected void onDetachedFromWindow() {
331 // Unhook the page indicator
332 mPageIndicator = null;
333 }
334
Adam Cohen7d30a372013-07-01 17:03:59 -0700335 void setDeleteDropTarget(View v) {
336 mDeleteDropTarget = v;
337 }
338
339 // Convenience methods to map points from self to parent and vice versa
340 float[] mapPointFromViewToParent(View v, float x, float y) {
341 mTmpPoint[0] = x;
342 mTmpPoint[1] = y;
343 v.getMatrix().mapPoints(mTmpPoint);
344 mTmpPoint[0] += v.getLeft();
345 mTmpPoint[1] += v.getTop();
346 return mTmpPoint;
347 }
348 float[] mapPointFromParentToView(View v, float x, float y) {
349 mTmpPoint[0] = x - v.getLeft();
350 mTmpPoint[1] = y - v.getTop();
351 v.getMatrix().invert(mTmpInvMatrix);
352 mTmpInvMatrix.mapPoints(mTmpPoint);
353 return mTmpPoint;
354 }
355
356 void updateDragViewTranslationDuringDrag() {
357 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
358 float y = mLastMotionY - mDownMotionY;
359 mDragView.setTranslationX(x);
360 mDragView.setTranslationY(y);
361
362 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
363 }
364
365 public void setMinScale(float f) {
366 mMinScale = f;
367 requestLayout();
368 }
369
370 @Override
371 public void setScaleX(float scaleX) {
372 super.setScaleX(scaleX);
373 if (isReordering(true)) {
374 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
375 mLastMotionX = p[0];
376 mLastMotionY = p[1];
377 updateDragViewTranslationDuringDrag();
378 }
379 }
380
381 // Convenience methods to get the actual width/height of the PagedView (since it is measured
382 // to be larger to account for the minimum possible scale)
383 int getViewportWidth() {
384 return mViewport.width();
385 }
386 int getViewportHeight() {
387 return mViewport.height();
388 }
389
390 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
391 // PagedView both horizontally and vertically
392 int getViewportOffsetX() {
393 return (getMeasuredWidth() - getViewportWidth()) / 2;
394 }
395
396 int getViewportOffsetY() {
397 return (getMeasuredHeight() - getViewportHeight()) / 2;
398 }
399
Winson Chung86f77532010-08-24 11:08:22 -0700400 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
401 mPageSwitchListener = pageSwitchListener;
402 if (mPageSwitchListener != null) {
403 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700404 }
405 }
406
407 /**
Winson Chung52aee602013-01-30 12:01:02 -0800408 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
409 */
410 public boolean isLayoutRtl() {
411 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
412 }
413
414 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700415 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
416 * out pages.
417 */
418 protected void setDataIsReady() {
419 mIsDataReady = true;
420 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700421
Winson Chungf0ea4d32011-06-06 14:27:16 -0700422 protected boolean isDataReady() {
423 return mIsDataReady;
424 }
425
426 /**
Winson Chung86f77532010-08-24 11:08:22 -0700427 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700428 *
Winson Chung86f77532010-08-24 11:08:22 -0700429 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700430 */
Winson Chung86f77532010-08-24 11:08:22 -0700431 int getCurrentPage() {
432 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700433 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700434
Winson Chung360e63f2012-04-27 13:48:05 -0700435 int getNextPage() {
436 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
437 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700438
Winson Chung86f77532010-08-24 11:08:22 -0700439 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700440 return getChildCount();
441 }
442
Winson Chung86f77532010-08-24 11:08:22 -0700443 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700444 return getChildAt(index);
445 }
446
Adam Cohenae4f1552011-10-20 00:15:42 -0700447 protected int indexToPage(int index) {
448 return index;
449 }
450
Winson Chung321e9ee2010-08-09 13:37:56 -0700451 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800452 * Updates the scroll of the current page immediately to its final scroll position. We use this
453 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
454 * the previous tab page.
455 */
456 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700457 // If the current page is invalid, just reset the scroll position to zero
458 int newX = 0;
459 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
460 int offset = getChildOffset(mCurrentPage);
461 int relOffset = getRelativeChildOffset(mCurrentPage);
462 newX = offset - relOffset;
463 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800464 scrollTo(newX, 0);
465 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800466 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800467 }
468
469 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700470 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
471 * ends, {@link #resumeScrolling()} should be called, along with
472 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
473 */
474 void pauseScrolling() {
475 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700476 }
477
478 /**
479 * Enables scrolling again.
480 * @see #pauseScrolling()
481 */
482 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700483 }
484 /**
Winson Chung86f77532010-08-24 11:08:22 -0700485 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700486 */
Winson Chung86f77532010-08-24 11:08:22 -0700487 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800488 if (!mScroller.isFinished()) {
489 mScroller.abortAnimation();
490 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800491 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
492 // the default
493 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800494 return;
495 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700496
Adam Cohene61a9a22013-06-11 15:45:31 -0700497 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700498 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700499 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800500 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700501 }
502
Michael Jurka0142d492010-08-25 17:46:15 -0700503 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700504 if (mPageSwitchListener != null) {
505 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700506 }
Winson Chungd2be3812013-07-16 11:11:32 -0700507
508 // Update the page indicator (when we aren't reordering)
509 if (mPageIndicator != null && !isReordering(false)) {
510 mPageIndicator.setActiveMarker(getNextPage());
511 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700512 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800513 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700514 if (!mIsPageMoving) {
515 mIsPageMoving = true;
516 onPageBeginMoving();
517 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700518 }
519
Michael Jurkace7e05f2011-02-01 22:02:35 -0800520 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700521 if (mIsPageMoving) {
522 mIsPageMoving = false;
523 onPageEndMoving();
524 }
Michael Jurka0142d492010-08-25 17:46:15 -0700525 }
526
Adam Cohen26976d92011-03-22 15:33:33 -0700527 protected boolean isPageMoving() {
528 return mIsPageMoving;
529 }
530
Michael Jurka0142d492010-08-25 17:46:15 -0700531 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700532 protected void onPageBeginMoving() {
533 }
534
535 // a method that subclasses can override to add behavior
536 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700537 }
538
Winson Chung321e9ee2010-08-09 13:37:56 -0700539 /**
Winson Chung86f77532010-08-24 11:08:22 -0700540 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700541 *
542 * @param l The listener used to respond to long clicks.
543 */
544 @Override
545 public void setOnLongClickListener(OnLongClickListener l) {
546 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700547 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700548 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700549 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700550 }
551 }
552
553 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800554 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700555 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800556 }
557
558 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700559 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700560 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800561 mUnboundedScrollX = x;
562
Adam Cohen0ffac432013-07-10 11:19:26 -0700563 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
564 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
565 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800566 super.scrollTo(0, y);
567 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700568 if (isRtl) {
569 overScroll(x - mMaxScrollX);
570 } else {
571 overScroll(x);
572 }
Adam Cohen68d73932010-11-15 10:50:58 -0800573 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700574 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800575 super.scrollTo(mMaxScrollX, y);
576 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700577 if (isRtl) {
578 overScroll(x);
579 } else {
580 overScroll(x - mMaxScrollX);
581 }
Adam Cohen68d73932010-11-15 10:50:58 -0800582 }
583 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800584 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800585 super.scrollTo(x, y);
586 }
587
Michael Jurka0142d492010-08-25 17:46:15 -0700588 mTouchX = x;
589 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700590
591 // Update the last motion events when scrolling
592 if (isReordering(true)) {
593 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
594 mLastMotionX = p[0];
595 mLastMotionY = p[1];
596 updateDragViewTranslationDuringDrag();
597 }
Michael Jurka0142d492010-08-25 17:46:15 -0700598 }
599
600 // we moved this functionality to a helper function so SmoothPagedView can reuse it
601 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700602 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700603 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700604 if (getScrollX() != mScroller.getCurrX()
605 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700606 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700607 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
608 }
Michael Jurka0142d492010-08-25 17:46:15 -0700609 invalidate();
610 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700611 } else if (mNextPage != INVALID_PAGE) {
612 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700613 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700614 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700615
Adam Cohen73aa9752010-11-24 16:26:58 -0800616 // We don't want to trigger a page end moving unless the page has settled
617 // and the user has stopped scrolling
618 if (mTouchState == TOUCH_STATE_REST) {
619 pageEndMoving();
620 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700621
Adam Cohen7d30a372013-07-01 17:03:59 -0700622 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700623 // Notify the user when the page changes
624 AccessibilityManager accessibilityManager = (AccessibilityManager)
625 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
626 if (accessibilityManager.isEnabled()) {
627 AccessibilityEvent ev =
628 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
629 ev.getText().add(getCurrentPageDescription());
630 sendAccessibilityEventUnchecked(ev);
631 }
Michael Jurka0142d492010-08-25 17:46:15 -0700632 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700633 }
Michael Jurka0142d492010-08-25 17:46:15 -0700634 return false;
635 }
636
637 @Override
638 public void computeScroll() {
639 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700640 }
641
Adam Cohen7d30a372013-07-01 17:03:59 -0700642 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
643 return mTopAlignPageWhenShrinkingForBouncer;
644 }
645
Adam Cohen96d30a12013-07-16 18:13:21 -0700646 public static class LayoutParams extends ViewGroup.LayoutParams {
647 public boolean isFullScreenPage = false;
648
649 /**
650 * {@inheritDoc}
651 */
652 public LayoutParams(int width, int height) {
653 super(width, height);
654 }
655
656 public LayoutParams(ViewGroup.LayoutParams source) {
657 super(source);
658 }
659 }
660
661 protected LayoutParams generateDefaultLayoutParams() {
662 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
663 }
664
665 public void addFullScreenPage(View page, int width, int height) {
666 LayoutParams lp = generateDefaultLayoutParams();
667 lp.isFullScreenPage = true;
668 super.addView(page, 0, lp);
669 }
670
Winson Chung321e9ee2010-08-09 13:37:56 -0700671 @Override
672 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700673 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700674 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
675 return;
676 }
677
Adam Cohen7d30a372013-07-01 17:03:59 -0700678 // We measure the dimensions of the PagedView to be larger than the pages so that when we
679 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700680 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
681 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
682 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700683 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700684 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
685 // viewport, we can be at most one and a half screens offset once we scale down
686 DisplayMetrics dm = getResources().getDisplayMetrics();
687 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
688 int parentWidthSize = (int) (1.5f * maxSize);
689 int parentHeightSize = maxSize;
690 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
691 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
692 mViewport.set(0, 0, widthSize, heightSize);
693
694 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
695 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
696 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700697 }
698
Winson Chung8aad6102012-05-11 16:27:49 -0700699 // Return early if we aren't given a proper dimension
700 if (widthSize <= 0 || heightSize <= 0) {
701 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
702 return;
703 }
704
Adam Lesinski6b879f02010-11-04 16:15:23 -0700705 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
706 * of the All apps view on XLarge displays to not take up more space then it needs. Width
707 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
708 * each page to have the same width.
709 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700710 final int verticalPadding = getPaddingTop() + getPaddingBottom();
711 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700712
713 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700714 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700715 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700716 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
717 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
718 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
719 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700720 final int childCount = getChildCount();
721 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700722 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700723 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700724 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
725
726 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700727 int childHeightMode;
728 int childWidth;
729 int childHeight;
730
731 if (!lp.isFullScreenPage) {
732 if (lp.width == LayoutParams.WRAP_CONTENT) {
733 childWidthMode = MeasureSpec.AT_MOST;
734 } else {
735 childWidthMode = MeasureSpec.EXACTLY;
736 }
737
738 if (lp.height == LayoutParams.WRAP_CONTENT) {
739 childHeightMode = MeasureSpec.AT_MOST;
740 } else {
741 childHeightMode = MeasureSpec.EXACTLY;
742 }
743
744 childWidth = widthSize - horizontalPadding;
745 childHeight = heightSize - verticalPadding;
746
Michael Jurka5f1c5092010-09-03 14:15:02 -0700747 } else {
748 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700749 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700750
751 childWidth = getViewportWidth();
752 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700753 }
754
755 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700756 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
757 final int childHeightMeasureSpec =
758 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700759 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700760 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700761 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700762
Winson Chung8aad6102012-05-11 16:27:49 -0700763 // We can't call getChildOffset/getRelativeChildOffset until we set the measured dimensions.
764 // We also wait until we set the measured dimensions before flushing the cache as well, to
765 // ensure that the cache is filled with good values.
766 invalidateCachedOffsets();
767
Winson Chunga128a7b2012-04-30 15:23:15 -0700768 if (childCount > 0) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700769 if (DEBUG) Log.d(TAG, "getRelativeChildOffset(): " + getViewportWidth() + ", "
Winson Chunga128a7b2012-04-30 15:23:15 -0700770 + getChildWidth(0));
771
772 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700773 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700774 // The gap between pages in the PagedView should be equal to the gap from the page
775 // to the edge of the screen (so it is not visible in the current screen). To
776 // account for unequal padding on each side of the paged view, we take the maximum
777 // of the left/right gap and use that as the gap between each page.
778 int offset = getRelativeChildOffset(0);
779 int spacing = Math.max(offset, widthSize - offset -
780 getChildAt(0).getMeasuredWidth());
781 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700782 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700783 }
784 }
785
Adam Cohen96d30a12013-07-16 18:13:21 -0700786 if (mScroller.isFinished() && mChildCountOnLastMeasure != getChildCount() &&
787 !mDeferringForDelete) {
788 setCurrentPage(getNextPage());
789 }
790 mChildCountOnLastMeasure = getChildCount();
791
Adam Cohenfaa28302010-11-19 12:02:18 -0800792 if (childCount > 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700793 final int index = isLayoutRtl() ? 0 : childCount - 1;
794 mMaxScrollX = getChildOffset(index) - getRelativeChildOffset(index);
Adam Cohenfaa28302010-11-19 12:02:18 -0800795 } else {
796 mMaxScrollX = 0;
797 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700798 }
799
Adam Cohen60b07122011-11-14 17:26:06 -0800800 public void setPageSpacing(int pageSpacing) {
801 mPageSpacing = pageSpacing;
802 invalidateCachedOffsets();
803 }
804
Winson Chung321e9ee2010-08-09 13:37:56 -0700805 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700806 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700807 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700808 return;
809 }
810
Winson Chung785d2eb2011-04-14 16:08:02 -0700811 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700812 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700813
Adam Cohen7d30a372013-07-01 17:03:59 -0700814 int offsetX = getViewportOffsetX();
815 int offsetY = getViewportOffsetY();
816
817 // Update the viewport offsets
818 mViewport.offset(offsetX, offsetY);
819
Adam Cohen0ffac432013-07-10 11:19:26 -0700820 final boolean isRtl = isLayoutRtl();
821
822 final int startIndex = isRtl ? childCount - 1 : 0;
823 final int endIndex = isRtl ? -1 : childCount;
824 final int delta = isRtl ? -1 : 1;
825
Adam Cohen7d30a372013-07-01 17:03:59 -0700826 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohen0ffac432013-07-10 11:19:26 -0700827 int childLeft = offsetX + getRelativeChildOffset(startIndex);
828 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700829 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700830 LayoutParams lp = (LayoutParams) child.getLayoutParams();
831 int childTop;
832
833 if (lp.isFullScreenPage) {
834 childTop = offsetY;
835 } else {
836 childTop = offsetY + getPaddingTop();
837 if (mCenterPagesVertically) {
838 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
839 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700840 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700841
Winson Chung321e9ee2010-08-09 13:37:56 -0700842 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700843 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700844 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800845
Winson Chung785d2eb2011-04-14 16:08:02 -0700846 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700847 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800848 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700849 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700850 }
851 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700852
853 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
854 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800855 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700856 setHorizontalScrollBarEnabled(true);
857 mFirstLayout = false;
858 }
Winson Chunge3193b92010-09-10 11:44:42 -0700859 }
860
Adam Cohenf34bab52010-09-30 14:11:56 -0700861 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700862 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
863
864 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700865 for (int i = 0; i < getChildCount(); i++) {
866 View child = getChildAt(i);
867 if (child != null) {
868 float scrollProgress = getScrollProgress(screenCenter, child, i);
869 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800870 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700871 }
872 }
873 invalidate();
874 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700875 }
876
Winson Chunge3193b92010-09-10 11:44:42 -0700877 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700878 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700879 // Update the page indicator, we don't update the page indicator as we
880 // add/remove pages
881 if (mPageIndicator != null && !isReordering(false)) {
882 mPageIndicator.addMarker(indexOfChild(child));
883 }
884
Adam Cohen2591f6a2011-10-25 14:36:40 -0700885 // This ensures that when children are added, they get the correct transforms / alphas
886 // in accordance with any scroll effects.
887 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700888 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700889
Adam Cohen2591f6a2011-10-25 14:36:40 -0700890 invalidate();
Adam Cohen25b29952011-11-02 14:49:06 -0700891 invalidateCachedOffsets();
Adam Cohen2591f6a2011-10-25 14:36:40 -0700892 }
893
Michael Jurka8b805b12012-04-18 14:23:14 -0700894 @Override
895 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700896 mForceScreenScrolled = true;
897 invalidate();
898 invalidateCachedOffsets();
Michael Jurka8b805b12012-04-18 14:23:14 -0700899 }
900
Winson Chungd2be3812013-07-16 11:11:32 -0700901 private void removeMarkerForView(int index) {
902 // Update the page indicator, we don't update the page indicator as we
903 // add/remove pages
904 if (mPageIndicator != null && !isReordering(false)) {
905 mPageIndicator.removeMarker(index);
906 }
907 }
908
909 @Override
910 public void removeView(View v) {
911 // XXX: We should find a better way to hook into this before the view
912 // gets removed form its parent...
913 removeMarkerForView(indexOfChild(v));
914 super.removeView(v);
915 }
916 @Override
917 public void removeViewInLayout(View v) {
918 // XXX: We should find a better way to hook into this before the view
919 // gets removed form its parent...
920 removeMarkerForView(indexOfChild(v));
921 super.removeViewInLayout(v);
922 }
923 @Override
924 public void removeViewAt(int index) {
925 // XXX: We should find a better way to hook into this before the view
926 // gets removed form its parent...
927 removeViewAt(index);
928 super.removeViewAt(index);
929 }
930 @Override
931 public void removeAllViewsInLayout() {
932 // Update the page indicator, we don't update the page indicator as we
933 // add/remove pages
934 if (mPageIndicator != null) {
935 mPageIndicator.removeAllMarkers();
936 }
937
938 super.removeAllViewsInLayout();
939 }
940
Adam Cohen73894962011-10-31 13:17:17 -0700941 protected void invalidateCachedOffsets() {
942 int count = getChildCount();
Adam Cohen25b29952011-11-02 14:49:06 -0700943 if (count == 0) {
944 mChildOffsets = null;
945 mChildRelativeOffsets = null;
Adam Cohen25b29952011-11-02 14:49:06 -0700946 return;
947 }
Adam Cohen73894962011-10-31 13:17:17 -0700948
949 mChildOffsets = new int[count];
950 mChildRelativeOffsets = new int[count];
Adam Cohen73894962011-10-31 13:17:17 -0700951 for (int i = 0; i < count; i++) {
952 mChildOffsets[i] = -1;
953 mChildRelativeOffsets[i] = -1;
Adam Cohen73894962011-10-31 13:17:17 -0700954 }
955 }
956
957 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700958 if (index < 0 || index > getChildCount() - 1) return 0;
959
Adam Cohen0ffac432013-07-10 11:19:26 -0700960 final boolean isRtl = isLayoutRtl();
Adam Cohen96d30a12013-07-16 18:13:21 -0700961 int[] childOffsets = mChildOffsets;
Adam Cohen73894962011-10-31 13:17:17 -0700962
963 if (childOffsets != null && childOffsets[index] != -1) {
964 return childOffsets[index];
965 } else {
966 if (getChildCount() == 0)
967 return 0;
968
Adam Cohen0ffac432013-07-10 11:19:26 -0700969 final int startIndex = isRtl ? getChildCount() - 1 : 0;
970 final int endIndex = isRtl ? index : index;
971 final int delta = isRtl ? -1 : 1;
972
973 int offset = getRelativeChildOffset(startIndex);
974 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700975 offset += getPageAt(i).getMeasuredWidth() + mPageSpacing;
Adam Cohen73894962011-10-31 13:17:17 -0700976 }
977 if (childOffsets != null) {
978 childOffsets[index] = offset;
979 }
980 return offset;
981 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700982
Adam Cohen73894962011-10-31 13:17:17 -0700983 }
984
985 protected int getRelativeChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700986 if (index < 0 || index > getChildCount() - 1) return 0;
987
Adam Cohen73894962011-10-31 13:17:17 -0700988 if (mChildRelativeOffsets != null && mChildRelativeOffsets[index] != -1) {
989 return mChildRelativeOffsets[index];
990 } else {
Michael Jurka8b805b12012-04-18 14:23:14 -0700991 final int padding = getPaddingLeft() + getPaddingRight();
992 final int offset = getPaddingLeft() +
Adam Cohen7d30a372013-07-01 17:03:59 -0700993 (getViewportWidth() - padding - getChildWidth(index)) / 2;
Adam Cohen73894962011-10-31 13:17:17 -0700994 if (mChildRelativeOffsets != null) {
995 mChildRelativeOffsets[index] = offset;
996 }
997 return offset;
998 }
999 }
1000
Adam Cohen7d30a372013-07-01 17:03:59 -07001001 void boundByReorderablePages(boolean isReordering, int[] range) {
1002 // Do nothing
1003 }
1004
1005 // TODO: Fix this
Michael Jurkadde558b2011-11-09 22:09:06 -08001006 protected void getVisiblePages(int[] range) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001007 range[0] = 0;
1008 range[1] = getPageCount() - 1;
1009
1010 /*
Michael Jurka0142d492010-08-25 17:46:15 -07001011 final int pageCount = getChildCount();
Michael Jurka4ff7d792012-04-02 03:46:50 -07001012
Michael Jurkac4fb9172010-09-02 17:19:20 -07001013 if (pageCount > 0) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001014 final int screenWidth = getViewportWidth();
1015 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -07001016 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001017 int offsetX = getViewportOffsetX() + getScrollX();
Michael Jurka47f74742012-03-02 13:39:13 -08001018 View currPage = getPageAt(leftScreen);
Adam Cohen7d30a372013-07-01 17:03:59 -07001019 while (leftScreen < pageCount - 1 &&
Michael Jurka8b805b12012-04-18 14:23:14 -07001020 currPage.getX() + currPage.getWidth() -
Adam Cohen7d30a372013-07-01 17:03:59 -07001021 currPage.getPaddingRight() < offsetX) {
1022 leftScreen++;
Michael Jurka47f74742012-03-02 13:39:13 -08001023 currPage = getPageAt(leftScreen);
Michael Jurkac4fb9172010-09-02 17:19:20 -07001024 }
1025 rightScreen = leftScreen;
Adam Cohen7d30a372013-07-01 17:03:59 -07001026 currPage = getPageAt(rightScreen + 1);
1027 while (rightScreen < pageCount - 1 &&
1028 currPage.getX() - currPage.getPaddingLeft() < offsetX + screenWidth) {
1029 rightScreen++;
1030 currPage = getPageAt(rightScreen + 1);
Michael Jurkac4fb9172010-09-02 17:19:20 -07001031 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001032
1033 // TEMP: this is a hacky way to ensure that animations to new pages are not clipped
1034 // because we don't draw them while scrolling?
1035 range[0] = Math.max(0, leftScreen - 1);
1036 range[1] = Math.min(rightScreen + 1, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001037 } else {
1038 range[0] = -1;
1039 range[1] = -1;
1040 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001041 */
Michael Jurkadde558b2011-11-09 22:09:06 -08001042 }
1043
Michael Jurka920d7f42012-05-14 16:29:55 -07001044 protected boolean shouldDrawChild(View child) {
1045 return child.getAlpha() > 0;
1046 }
1047
Michael Jurkadde558b2011-11-09 22:09:06 -08001048 @Override
1049 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001050 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001051 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1052 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001053 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001054
1055 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001056 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1057 // set it for the next frame
1058 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001059 screenScrolled(screenCenter);
1060 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001061 }
1062
1063 // Find out which screens are visible; as an optimization we only call draw on them
1064 final int pageCount = getChildCount();
1065 if (pageCount > 0) {
1066 getVisiblePages(mTempVisiblePagesRange);
1067 final int leftScreen = mTempVisiblePagesRange[0];
1068 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001069 if (leftScreen != -1 && rightScreen != -1) {
1070 final long drawingTime = getDrawingTime();
1071 // Clip to the bounds
1072 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001073 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1074 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001075
Adam Cohen7d30a372013-07-01 17:03:59 -07001076 // Draw all the children, leaving the drag view for last
1077 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001078 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001079 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001080 if (mForceDrawAllChildrenNextFrame ||
1081 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001082 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001083 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001084 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001085 // Draw the drag view on top (if there is one)
1086 if (mDragView != null) {
1087 drawChild(canvas, mDragView, drawingTime);
1088 }
1089
Michael Jurka5e368ff2012-05-14 23:13:15 -07001090 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001091 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001092 }
Michael Jurka0142d492010-08-25 17:46:15 -07001093 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001094 }
1095
1096 @Override
1097 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001098 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001099 if (page != mCurrentPage || !mScroller.isFinished()) {
1100 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001101 return true;
1102 }
1103 return false;
1104 }
1105
1106 @Override
1107 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001108 int focusablePage;
1109 if (mNextPage != INVALID_PAGE) {
1110 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001111 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001112 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001113 }
Winson Chung86f77532010-08-24 11:08:22 -07001114 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001115 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001116 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001117 }
1118 return false;
1119 }
1120
1121 @Override
1122 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001123 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001124 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001125 if (getCurrentPage() > 0) {
1126 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001127 return true;
1128 }
1129 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001130 if (getCurrentPage() < getPageCount() - 1) {
1131 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001132 return true;
1133 }
1134 }
1135 return super.dispatchUnhandledMove(focused, direction);
1136 }
1137
1138 @Override
1139 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001140 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001141 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001142 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001143 }
1144 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001145 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001146 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001147 }
1148 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001149 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001150 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001151 }
1152 }
1153 }
1154
1155 /**
1156 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001157 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001158 *
Winson Chung86f77532010-08-24 11:08:22 -07001159 * This happens when live folders requery, and if they're off page, they
1160 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001161 */
1162 @Override
1163 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001164 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001165 View v = focused;
1166 while (true) {
1167 if (v == current) {
1168 super.focusableViewAvailable(focused);
1169 return;
1170 }
1171 if (v == this) {
1172 return;
1173 }
1174 ViewParent parent = v.getParent();
1175 if (parent instanceof View) {
1176 v = (View)v.getParent();
1177 } else {
1178 return;
1179 }
1180 }
1181 }
1182
1183 /**
1184 * {@inheritDoc}
1185 */
1186 @Override
1187 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1188 if (disallowIntercept) {
1189 // We need to make sure to cancel our long press if
1190 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001191 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001192 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001193 }
1194 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1195 }
1196
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001197 /**
1198 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1199 */
1200 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001201 if (isLayoutRtl()) {
1202 return (x > (getViewportOffsetX() + getViewportWidth() -
1203 getRelativeChildOffset(mCurrentPage) + mPageSpacing));
1204 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001205 return (x < getViewportOffsetX() + getRelativeChildOffset(mCurrentPage) - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001206 }
1207
1208 /**
1209 * Return true if a tap at (x, y) should trigger a flip to the next page.
1210 */
1211 protected boolean hitsNextPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001212 if (isLayoutRtl()) {
1213 return (x < getViewportOffsetX() + getRelativeChildOffset(mCurrentPage) - mPageSpacing);
1214 }
1215 return (x > (getViewportOffsetX() + getViewportWidth() -
1216 getRelativeChildOffset(mCurrentPage) + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001217 }
Winson Chung52aee602013-01-30 12:01:02 -08001218
Adam Cohen7d30a372013-07-01 17:03:59 -07001219 /** Returns whether x and y originated within the buffered viewport */
1220 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1221 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1222 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1223 return mTmpRect.contains(x, y);
1224 }
1225
1226 /** Returns whether x and y originated within the current page view bounds */
1227 private boolean isTouchPointInCurrentPage(int x, int y) {
1228 View v = getPageAt(getCurrentPage());
1229 if (v != null) {
1230 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1231 v.getBottom());
1232 return mTmpRect.contains(x, y);
1233 }
1234 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001235 }
1236
Winson Chung321e9ee2010-08-09 13:37:56 -07001237 @Override
1238 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001239 if (DISABLE_TOUCH_INTERACTION) {
1240 return false;
1241 }
1242
Winson Chung321e9ee2010-08-09 13:37:56 -07001243 /*
1244 * This method JUST determines whether we want to intercept the motion.
1245 * If we return true, onTouchEvent will be called and we do the actual
1246 * scrolling there.
1247 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001248 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001249
Winson Chung45e1d6e2010-11-09 17:19:49 -08001250 // Skip touch handling if there are no pages to swipe
1251 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1252
Winson Chung321e9ee2010-08-09 13:37:56 -07001253 /*
1254 * Shortcut the most recurring case: the user is in the dragging
1255 * state and he is moving his finger. We want to intercept this
1256 * motion.
1257 */
1258 final int action = ev.getAction();
1259 if ((action == MotionEvent.ACTION_MOVE) &&
1260 (mTouchState == TOUCH_STATE_SCROLLING)) {
1261 return true;
1262 }
1263
Winson Chung321e9ee2010-08-09 13:37:56 -07001264 switch (action & MotionEvent.ACTION_MASK) {
1265 case MotionEvent.ACTION_MOVE: {
1266 /*
1267 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1268 * whether the user has moved far enough from his original down touch.
1269 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001270 if (mActivePointerId != INVALID_POINTER) {
1271 determineScrollingStart(ev);
1272 break;
1273 }
1274 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1275 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1276 // i.e. fall through to the next case (don't break)
1277 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1278 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001279 }
1280
1281 case MotionEvent.ACTION_DOWN: {
1282 final float x = ev.getX();
1283 final float y = ev.getY();
1284 // Remember location of down touch
1285 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001286 mDownMotionY = y;
1287 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001288 mLastMotionX = x;
1289 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001290 float[] p = mapPointFromViewToParent(this, x, y);
1291 mParentDownMotionX = p[0];
1292 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001293 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001294 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001295 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001296
1297 // Determine if the down event is within the threshold to be an edge swipe
1298 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1299 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1300 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1301 mDownEventOnEdge = true;
1302 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001303
1304 /*
1305 * If being flinged and user touches the screen, initiate drag;
1306 * otherwise don't. mScroller.isFinished should be false when
1307 * being flinged.
1308 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001309 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001310 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1311 if (finishedScrolling) {
1312 mTouchState = TOUCH_STATE_REST;
1313 mScroller.abortAnimation();
1314 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001315 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1316 mTouchState = TOUCH_STATE_SCROLLING;
1317 } else {
1318 mTouchState = TOUCH_STATE_REST;
1319 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001320 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001321
Winson Chung86f77532010-08-24 11:08:22 -07001322 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001323 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001324 if (!DISABLE_TOUCH_SIDE_PAGES) {
1325 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1326 if (getChildCount() > 0) {
1327 if (hitsPreviousPage(x, y)) {
1328 mTouchState = TOUCH_STATE_PREV_PAGE;
1329 } else if (hitsNextPage(x, y)) {
1330 mTouchState = TOUCH_STATE_NEXT_PAGE;
1331 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001332 }
1333 }
1334 }
1335 break;
1336 }
1337
Winson Chung321e9ee2010-08-09 13:37:56 -07001338 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001339 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001340 resetTouchState();
1341 // Just intercept the touch event on up if we tap outside the strict viewport
1342 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1343 return true;
1344 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001345 break;
1346
1347 case MotionEvent.ACTION_POINTER_UP:
1348 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001349 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001350 break;
1351 }
1352
1353 /*
1354 * The only time we want to intercept motion events is if we are in the
1355 * drag mode.
1356 */
1357 return mTouchState != TOUCH_STATE_REST;
1358 }
1359
Adam Cohenf8d28232011-02-01 21:47:00 -08001360 protected void determineScrollingStart(MotionEvent ev) {
1361 determineScrollingStart(ev, 1.0f);
1362 }
1363
Winson Chung321e9ee2010-08-09 13:37:56 -07001364 /*
1365 * Determines if we should change the touch state to start scrolling after the
1366 * user moves their touch point too far.
1367 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001368 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001369 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001370 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001371 if (pointerIndex == -1) return;
1372
1373 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001374 final float x = ev.getX(pointerIndex);
1375 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001376 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1377
1378 // If we're only allowing edge swipes, we break out early if the down event wasn't
1379 // at the edge.
1380 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1381
Winson Chung321e9ee2010-08-09 13:37:56 -07001382 final int xDiff = (int) Math.abs(x - mLastMotionX);
1383 final int yDiff = (int) Math.abs(y - mLastMotionY);
1384
Adam Cohenf8d28232011-02-01 21:47:00 -08001385 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001386 boolean xPaged = xDiff > mPagingTouchSlop;
1387 boolean xMoved = xDiff > touchSlop;
1388 boolean yMoved = yDiff > touchSlop;
1389
Adam Cohenf8d28232011-02-01 21:47:00 -08001390 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001391 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001392 // Scroll if the user moved far enough along the X axis
1393 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001394 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001395 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001396 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001397 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001398 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1399 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001400 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001401 }
1402 }
1403
Adam Cohen7d30a372013-07-01 17:03:59 -07001404 protected float getMaxScrollProgress() {
1405 return 1.0f;
1406 }
1407
Adam Cohenf8d28232011-02-01 21:47:00 -08001408 protected void cancelCurrentPageLongPress() {
1409 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001410 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001411 // Try canceling the long press. It could also have been scheduled
1412 // by a distant descendant, so use the mAllowLongPress flag to block
1413 // everything
1414 final View currentPage = getPageAt(mCurrentPage);
1415 if (currentPage != null) {
1416 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001417 }
1418 }
1419 }
1420
Adam Cohen7d30a372013-07-01 17:03:59 -07001421 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1422 final int halfScreenSize = getViewportWidth() / 2;
1423
1424 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1425 screenCenter = Math.max(halfScreenSize, screenCenter);
1426
1427 return getScrollProgress(screenCenter, v, page);
1428 }
1429
Adam Cohenb5ba0972011-09-07 18:02:31 -07001430 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001431 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001432
Adam Cohen96d30a12013-07-16 18:13:21 -07001433 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001434 int delta = screenCenter - (getChildOffset(page) -
1435 getRelativeChildOffset(page) + halfScreenSize);
1436
1437 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001438 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1439 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001440 return scrollProgress;
1441 }
1442
Adam Cohene0f66b52010-11-23 15:06:07 -08001443 // This curve determines how the effect of scrolling over the limits of the page dimishes
1444 // as the user pulls further and further from the bounds
1445 private float overScrollInfluenceCurve(float f) {
1446 f -= 1.0f;
1447 return f * f * f + 1.0f;
1448 }
1449
Adam Cohenb5ba0972011-09-07 18:02:31 -07001450 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001451 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001452
1453 // We want to reach the max over scroll effect when the user has
1454 // over scrolled half the size of the screen
1455 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1456
1457 if (f == 0) return;
1458
1459 // Clamp this factor, f, to -1 < f < 1
1460 if (Math.abs(f) >= 1) {
1461 f /= Math.abs(f);
1462 }
1463
1464 int overScrollAmount = (int) Math.round(f * screenSize);
1465 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001466 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001467 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001468 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001469 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001470 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001471 }
1472 invalidate();
1473 }
1474
1475 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001476 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001477
1478 float f = (amount / screenSize);
1479
1480 if (f == 0) return;
1481 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1482
Adam Cohen7bfc9792011-01-28 13:52:37 -08001483 // Clamp this factor, f, to -1 < f < 1
1484 if (Math.abs(f) >= 1) {
1485 f /= Math.abs(f);
1486 }
1487
Adam Cohene0f66b52010-11-23 15:06:07 -08001488 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001489 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001490 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001491 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001492 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001493 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001494 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001495 }
1496 invalidate();
1497 }
1498
Adam Cohenb5ba0972011-09-07 18:02:31 -07001499 protected void overScroll(float amount) {
1500 dampedOverScroll(amount);
1501 }
1502
Michael Jurkac5b262c2011-01-12 20:24:50 -08001503 protected float maxOverScroll() {
1504 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001505 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001506 float f = 1.0f;
1507 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1508 return OVERSCROLL_DAMP_FACTOR * f;
1509 }
1510
Winson Chung321e9ee2010-08-09 13:37:56 -07001511 @Override
1512 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001513 if (DISABLE_TOUCH_INTERACTION) {
1514 return false;
1515 }
1516
Winson Chung45e1d6e2010-11-09 17:19:49 -08001517 // Skip touch handling if there are no pages to swipe
1518 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1519
Michael Jurkab8f06722010-10-10 15:58:46 -07001520 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001521
1522 final int action = ev.getAction();
1523
1524 switch (action & MotionEvent.ACTION_MASK) {
1525 case MotionEvent.ACTION_DOWN:
1526 /*
1527 * If being flinged and user touches, stop the fling. isFinished
1528 * will be false if being flinged.
1529 */
1530 if (!mScroller.isFinished()) {
1531 mScroller.abortAnimation();
1532 }
1533
1534 // Remember where the motion event started
1535 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001536 mDownMotionY = mLastMotionY = ev.getY();
1537 mDownScrollX = getScrollX();
1538 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1539 mParentDownMotionX = p[0];
1540 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001541 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001542 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001543 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001544
1545 // Determine if the down event is within the threshold to be an edge swipe
1546 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1547 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1548 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1549 mDownEventOnEdge = true;
1550 }
1551
Michael Jurka0142d492010-08-25 17:46:15 -07001552 if (mTouchState == TOUCH_STATE_SCROLLING) {
1553 pageBeginMoving();
1554 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001555 break;
1556
1557 case MotionEvent.ACTION_MOVE:
1558 if (mTouchState == TOUCH_STATE_SCROLLING) {
1559 // Scroll to follow the motion event
1560 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001561
1562 if (pointerIndex == -1) return true;
1563
Winson Chung321e9ee2010-08-09 13:37:56 -07001564 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001565 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001566
Adam Cohenaefd4e12011-02-14 16:39:38 -08001567 mTotalMotionX += Math.abs(deltaX);
1568
Winson Chungc0844aa2011-02-02 15:25:58 -08001569 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1570 // keep the remainder because we are actually testing if we've moved from the last
1571 // scrolled position (which is discrete).
1572 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001573 mTouchX += deltaX;
1574 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1575 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001576 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001577 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001578 } else {
1579 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001580 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001581 mLastMotionX = x;
1582 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001583 } else {
1584 awakenScrollBars();
1585 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001586 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1587 // Update the last motion position
1588 mLastMotionX = ev.getX();
1589 mLastMotionY = ev.getY();
1590
1591 // Update the parent down so that our zoom animations take this new movement into
1592 // account
1593 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1594 mParentDownMotionX = pt[0];
1595 mParentDownMotionY = pt[1];
1596 updateDragViewTranslationDuringDrag();
1597
1598 // Find the closest page to the touch point
1599 final int dragViewIndex = indexOfChild(mDragView);
1600 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1601 getViewportWidth());
1602 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1603 + bufferSize);
1604 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1605 - bufferSize);
1606
1607 // Change the drag view if we are hovering over the drop target
1608 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1609 (int) mParentDownMotionX, (int) mParentDownMotionY);
1610 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1611
1612 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1613 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1614 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1615 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1616 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1617 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1618
1619 float parentX = mParentDownMotionX;
1620 int pageIndexToSnapTo = -1;
1621 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1622 pageIndexToSnapTo = dragViewIndex - 1;
1623 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1624 pageIndexToSnapTo = dragViewIndex + 1;
1625 }
1626
1627 final int pageUnderPointIndex = pageIndexToSnapTo;
1628 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1629 mTempVisiblePagesRange[0] = 0;
1630 mTempVisiblePagesRange[1] = getPageCount() - 1;
1631 boundByReorderablePages(true, mTempVisiblePagesRange);
1632 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1633 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1634 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1635 mSidePageHoverIndex = pageUnderPointIndex;
1636 mSidePageHoverRunnable = new Runnable() {
1637 @Override
1638 public void run() {
1639 // Update the down scroll position to account for the fact that the
1640 // current page is moved
1641 mDownScrollX = getChildOffset(pageUnderPointIndex)
1642 - getRelativeChildOffset(pageUnderPointIndex);
1643
1644 // Setup the scroll to the correct page before we swap the views
1645 snapToPage(pageUnderPointIndex);
1646
1647 // For each of the pages between the paged view and the drag view,
1648 // animate them from the previous position to the new position in
1649 // the layout (as a result of the drag view moving in the layout)
1650 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1651 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1652 dragViewIndex + 1 : pageUnderPointIndex;
1653 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1654 dragViewIndex - 1 : pageUnderPointIndex;
1655 for (int i = lowerIndex; i <= upperIndex; ++i) {
1656 View v = getChildAt(i);
1657 // dragViewIndex < pageUnderPointIndex, so after we remove the
1658 // drag view all subsequent views to pageUnderPointIndex will
1659 // shift down.
1660 int oldX = getViewportOffsetX() + getChildOffset(i);
1661 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1662
1663 // Animate the view translation from its old position to its new
1664 // position
1665 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1666 if (anim != null) {
1667 anim.cancel();
1668 }
1669
1670 v.setTranslationX(oldX - newX);
1671 anim = new AnimatorSet();
1672 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1673 anim.playTogether(
1674 ObjectAnimator.ofFloat(v, "translationX", 0f));
1675 anim.start();
1676 v.setTag(anim);
1677 }
1678
1679 removeView(mDragView);
1680 onRemoveView(mDragView, false);
1681 addView(mDragView, pageUnderPointIndex);
1682 onAddView(mDragView, pageUnderPointIndex);
1683 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001684 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001685 }
1686 };
1687 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1688 }
1689 } else {
1690 removeCallbacks(mSidePageHoverRunnable);
1691 mSidePageHoverIndex = -1;
1692 }
Adam Cohen564976a2010-10-13 18:52:07 -07001693 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001694 determineScrollingStart(ev);
1695 }
1696 break;
1697
1698 case MotionEvent.ACTION_UP:
1699 if (mTouchState == TOUCH_STATE_SCROLLING) {
1700 final int activePointerId = mActivePointerId;
1701 final int pointerIndex = ev.findPointerIndex(activePointerId);
1702 final float x = ev.getX(pointerIndex);
1703 final VelocityTracker velocityTracker = mVelocityTracker;
1704 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1705 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001706 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001707 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001708 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1709 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001710
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001711 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1712
Adam Cohen00481b32011-11-18 12:03:48 -08001713 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001714 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001715
Adam Cohenaefd4e12011-02-14 16:39:38 -08001716 // In the case that the page is moved far to one direction and then is flung
1717 // in the opposite direction, we use a threshold to determine whether we should
1718 // just return to the starting page, or if we should skip one further.
1719 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001720 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001721 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001722 returnToOriginalPage = true;
1723 }
1724
Adam Cohenaefd4e12011-02-14 16:39:38 -08001725 int finalPage;
1726 // We give flings precedence over large moves, which is why we short-circuit our
1727 // test for a large move if a fling has been registered. That is, a large
1728 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001729 final boolean isRtl = isLayoutRtl();
1730 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1731 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1732 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1733 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001734 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1735 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001736 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1737 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001738 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001739 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1740 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001741 } else {
1742 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001743 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001744 // at this point we have not moved beyond the touch slop
1745 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1746 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001747 int nextPage = Math.max(0, mCurrentPage - 1);
1748 if (nextPage != mCurrentPage) {
1749 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001750 } else {
1751 snapToDestination();
1752 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001753 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001754 // at this point we have not moved beyond the touch slop
1755 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1756 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001757 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1758 if (nextPage != mCurrentPage) {
1759 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001760 } else {
1761 snapToDestination();
1762 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001763 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1764 // Update the last motion position
1765 mLastMotionX = ev.getX();
1766 mLastMotionY = ev.getY();
1767
1768 // Update the parent down so that our zoom animations take this new movement into
1769 // account
1770 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1771 mParentDownMotionX = pt[0];
1772 mParentDownMotionY = pt[1];
1773 updateDragViewTranslationDuringDrag();
1774 boolean handledFling = false;
1775 if (!DISABLE_FLING_TO_DELETE) {
1776 // Check the velocity and see if we are flinging-to-delete
1777 PointF flingToDeleteVector = isFlingingToDelete();
1778 if (flingToDeleteVector != null) {
1779 onFlingToDelete(flingToDeleteVector);
1780 handledFling = true;
1781 }
1782 }
1783 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1784 (int) mParentDownMotionY)) {
1785 onDropToDelete();
1786 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001787 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001788 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001789 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001790
1791 // Remove the callback to wait for the side page hover timeout
1792 removeCallbacks(mSidePageHoverRunnable);
1793 // End any intermediate reordering states
1794 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001795 break;
1796
1797 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001798 if (mTouchState == TOUCH_STATE_SCROLLING) {
1799 snapToDestination();
1800 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001801 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001802 break;
1803
1804 case MotionEvent.ACTION_POINTER_UP:
1805 onSecondaryPointerUp(ev);
1806 break;
1807 }
1808
1809 return true;
1810 }
1811
Adam Cohen7d30a372013-07-01 17:03:59 -07001812 public void onFlingToDelete(View v) {}
1813 public void onRemoveView(View v, boolean deletePermanently) {}
1814 public void onRemoveViewAnimationCompleted() {}
1815 public void onAddView(View v, int index) {}
1816
1817 private void resetTouchState() {
1818 releaseVelocityTracker();
1819 endReordering();
1820 mTouchState = TOUCH_STATE_REST;
1821 mActivePointerId = INVALID_POINTER;
1822 mDownEventOnEdge = false;
1823 }
1824
1825 protected void onUnhandledTap(MotionEvent ev) {}
1826
Winson Chung185d7162011-02-28 13:47:29 -08001827 @Override
1828 public boolean onGenericMotionEvent(MotionEvent event) {
1829 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1830 switch (event.getAction()) {
1831 case MotionEvent.ACTION_SCROLL: {
1832 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1833 final float vscroll;
1834 final float hscroll;
1835 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1836 vscroll = 0;
1837 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1838 } else {
1839 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1840 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1841 }
1842 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001843 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1844 : (hscroll > 0 || vscroll > 0);
1845 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001846 scrollRight();
1847 } else {
1848 scrollLeft();
1849 }
1850 return true;
1851 }
1852 }
1853 }
1854 }
1855 return super.onGenericMotionEvent(event);
1856 }
1857
Michael Jurkab8f06722010-10-10 15:58:46 -07001858 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1859 if (mVelocityTracker == null) {
1860 mVelocityTracker = VelocityTracker.obtain();
1861 }
1862 mVelocityTracker.addMovement(ev);
1863 }
1864
1865 private void releaseVelocityTracker() {
1866 if (mVelocityTracker != null) {
1867 mVelocityTracker.recycle();
1868 mVelocityTracker = null;
1869 }
1870 }
1871
Winson Chung321e9ee2010-08-09 13:37:56 -07001872 private void onSecondaryPointerUp(MotionEvent ev) {
1873 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1874 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1875 final int pointerId = ev.getPointerId(pointerIndex);
1876 if (pointerId == mActivePointerId) {
1877 // This was our active pointer going up. Choose a new
1878 // active pointer and adjust accordingly.
1879 // TODO: Make this decision more intelligent.
1880 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1881 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1882 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001883 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001884 mActivePointerId = ev.getPointerId(newPointerIndex);
1885 if (mVelocityTracker != null) {
1886 mVelocityTracker.clear();
1887 }
1888 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001889 }
1890
Winson Chung321e9ee2010-08-09 13:37:56 -07001891 @Override
1892 public void requestChildFocus(View child, View focused) {
1893 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001894 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001895 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001896 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001897 }
1898 }
1899
Winson Chung1908d072011-02-24 18:09:44 -08001900 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001901 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001902 }
1903
Adam Cohen7d30a372013-07-01 17:03:59 -07001904 int getPageNearestToPoint(float x) {
1905 int index = 0;
1906 for (int i = 0; i < getChildCount(); ++i) {
1907 if (x < getChildAt(i).getRight() - getScrollX()) {
1908 return index;
1909 } else {
1910 index++;
1911 }
1912 }
1913 return Math.min(index, getChildCount() - 1);
1914 }
1915
Adam Cohend19d3ca2010-09-15 14:43:42 -07001916 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001917 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001918 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001919 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001920 final int childCount = getChildCount();
1921 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001922 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001923 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001924 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001925 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001926 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1927 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1928 minDistanceFromScreenCenter = distanceFromScreenCenter;
1929 minDistanceFromScreenCenterIndex = i;
1930 }
1931 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001932 return minDistanceFromScreenCenterIndex;
1933 }
1934
1935 protected void snapToDestination() {
1936 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001937 }
1938
Adam Cohene0f66b52010-11-23 15:06:07 -08001939 private static class ScrollInterpolator implements Interpolator {
1940 public ScrollInterpolator() {
1941 }
1942
1943 public float getInterpolation(float t) {
1944 t -= 1.0f;
1945 return t*t*t*t*t + 1;
1946 }
1947 }
1948
1949 // We want the duration of the page snap animation to be influenced by the distance that
1950 // the screen has to travel, however, we don't want this duration to be effected in a
1951 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1952 // of travel has on the overall snap duration.
1953 float distanceInfluenceForSnapDuration(float f) {
1954 f -= 0.5f; // center the values about 0.
1955 f *= 0.3f * Math.PI / 2.0f;
1956 return (float) Math.sin(f);
1957 }
1958
Michael Jurka0142d492010-08-25 17:46:15 -07001959 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001960 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001961 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001962
Winson Chung785d2eb2011-04-14 16:08:02 -07001963 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage));
1964 if (DEBUG) Log.d(TAG, "snapToPageWithVelocity.getRelativeChildOffset(): "
Adam Cohen7d30a372013-07-01 17:03:59 -07001965 + getViewportWidth() + ", " + getChildWidth(whichPage));
Adam Cohene0f66b52010-11-23 15:06:07 -08001966 final int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
1967 int delta = newX - mUnboundedScrollX;
1968 int duration = 0;
1969
Adam Cohen265b9a62011-12-07 14:37:18 -08001970 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001971 // If the velocity is low enough, then treat this more as an automatic page advance
1972 // as opposed to an apparent physical response to flinging
1973 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1974 return;
1975 }
1976
1977 // Here we compute a "distance" that will be used in the computation of the overall
1978 // snap duration. This is a function of the actual distance that needs to be traveled;
1979 // we keep this value close to half screen size in order to reduce the variance in snap
1980 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001981 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001982 float distance = halfScreenSize + halfScreenSize *
1983 distanceInfluenceForSnapDuration(distanceRatio);
1984
1985 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001986 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001987
1988 // we want the page's snap velocity to approximately match the velocity at which the
1989 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001990 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1991 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001992
1993 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001994 }
1995
1996 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001997 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001998 }
1999
Adam Cohen7d30a372013-07-01 17:03:59 -07002000 protected void snapToPageImmediately(int whichPage) {
2001 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2002 }
2003
Michael Jurka0142d492010-08-25 17:46:15 -07002004 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002005 snapToPage(whichPage, duration, false);
2006 }
2007
2008 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002009 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002010
Winson Chung785d2eb2011-04-14 16:08:02 -07002011 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage));
Adam Cohen7d30a372013-07-01 17:03:59 -07002012 if (DEBUG) Log.d(TAG, "snapToPage.getRelativeChildOffset(): " + getViewportWidth() + ", "
Winson Chung785d2eb2011-04-14 16:08:02 -07002013 + getChildWidth(whichPage));
Winson Chung86f77532010-08-24 11:08:22 -07002014 int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002015 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002016 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002017 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002018 }
2019
2020 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002021 snapToPage(whichPage, delta, duration, false);
2022 }
Michael Jurka0142d492010-08-25 17:46:15 -07002023
Adam Cohen7d30a372013-07-01 17:03:59 -07002024 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2025 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002026 View focusedChild = getFocusedChild();
2027 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002028 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002029 focusedChild.clearFocus();
2030 }
2031
2032 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002033 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002034 if (immediate) {
2035 duration = 0;
2036 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002037 duration = Math.abs(delta);
2038 }
2039
2040 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002041 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002042
Michael Jurka0142d492010-08-25 17:46:15 -07002043 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002044
2045 // Trigger a compute() to finish switching pages if necessary
2046 if (immediate) {
2047 computeScroll();
2048 }
2049
2050 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002051 invalidate();
2052 }
2053
Winson Chung321e9ee2010-08-09 13:37:56 -07002054 public void scrollLeft() {
2055 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002056 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002057 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002058 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002059 }
2060 }
2061
2062 public void scrollRight() {
2063 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002064 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002065 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002066 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002067 }
2068 }
2069
Winson Chung86f77532010-08-24 11:08:22 -07002070 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002071 int result = -1;
2072 if (v != null) {
2073 ViewParent vp = v.getParent();
2074 int count = getChildCount();
2075 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002076 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002077 return i;
2078 }
2079 }
2080 }
2081 return result;
2082 }
2083
2084 /**
2085 * @return True is long presses are still allowed for the current touch
2086 */
2087 public boolean allowLongPress() {
2088 return mAllowLongPress;
2089 }
2090
Michael Jurka0142d492010-08-25 17:46:15 -07002091 /**
2092 * Set true to allow long-press events to be triggered, usually checked by
2093 * {@link Launcher} to accept or block dpad-initiated long-presses.
2094 */
2095 public void setAllowLongPress(boolean allowLongPress) {
2096 mAllowLongPress = allowLongPress;
2097 }
2098
Winson Chung321e9ee2010-08-09 13:37:56 -07002099 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002100 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002101
2102 SavedState(Parcelable superState) {
2103 super(superState);
2104 }
2105
2106 private SavedState(Parcel in) {
2107 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002108 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002109 }
2110
2111 @Override
2112 public void writeToParcel(Parcel out, int flags) {
2113 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002114 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002115 }
2116
2117 public static final Parcelable.Creator<SavedState> CREATOR =
2118 new Parcelable.Creator<SavedState>() {
2119 public SavedState createFromParcel(Parcel in) {
2120 return new SavedState(in);
2121 }
2122
2123 public SavedState[] newArray(int size) {
2124 return new SavedState[size];
2125 }
2126 };
2127 }
2128
Winson Chungf314b0e2011-08-16 11:54:27 -07002129 protected void loadAssociatedPages(int page) {
2130 loadAssociatedPages(page, false);
2131 }
2132 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002133 if (mContentIsRefreshable) {
2134 final int count = getChildCount();
2135 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002136 int lowerPageBound = getAssociatedLowerPageBound(page);
2137 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002138 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2139 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002140 // First, clear any pages that should no longer be loaded
2141 for (int i = 0; i < count; ++i) {
2142 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002143 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002144 if (layout.getPageChildCount() > 0) {
2145 layout.removeAllViewsOnPage();
2146 }
2147 mDirtyPageContent.set(i, true);
2148 }
2149 }
2150 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002151 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002152 if ((i != page) && immediateAndOnly) {
2153 continue;
2154 }
Michael Jurka0142d492010-08-25 17:46:15 -07002155 if (lowerPageBound <= i && i <= upperPageBound) {
2156 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002157 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002158 mDirtyPageContent.set(i, false);
2159 }
Winson Chung86f77532010-08-24 11:08:22 -07002160 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002161 }
2162 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002163 }
2164 }
2165
Winson Chunge3193b92010-09-10 11:44:42 -07002166 protected int getAssociatedLowerPageBound(int page) {
2167 return Math.max(0, page - 1);
2168 }
2169 protected int getAssociatedUpperPageBound(int page) {
2170 final int count = getChildCount();
2171 return Math.min(page + 1, count - 1);
2172 }
2173
Winson Chung86f77532010-08-24 11:08:22 -07002174 /**
2175 * This method is called ONLY to synchronize the number of pages that the paged view has.
2176 * To actually fill the pages with information, implement syncPageItems() below. It is
2177 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2178 * and therefore, individual page items do not need to be updated in this method.
2179 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002180 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002181
2182 /**
2183 * This method is called to synchronize the items that are on a particular page. If views on
2184 * the page can be reused, then they should be updated within this method.
2185 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002186 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002187
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002188 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002189 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002190 }
2191 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002192 invalidatePageData(currentPage, false);
2193 }
2194 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002195 if (!mIsDataReady) {
2196 return;
2197 }
2198
Michael Jurka0142d492010-08-25 17:46:15 -07002199 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002200 // Force all scrolling-related behavior to end
2201 mScroller.forceFinished(true);
2202 mNextPage = INVALID_PAGE;
2203
Michael Jurka0142d492010-08-25 17:46:15 -07002204 // Update all the pages
2205 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002206
Winson Chung5a808352011-06-27 19:08:49 -07002207 // We must force a measure after we've loaded the pages to update the content width and
2208 // to determine the full scroll width
2209 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2210 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2211
2212 // Set a new page as the current page if necessary
2213 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002214 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002215 }
2216
Michael Jurka0142d492010-08-25 17:46:15 -07002217 // Mark each of the pages as dirty
2218 final int count = getChildCount();
2219 mDirtyPageContent.clear();
2220 for (int i = 0; i < count; ++i) {
2221 mDirtyPageContent.add(true);
2222 }
2223
2224 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002225 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002226 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002227 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002228 }
Winson Chung007c6982011-06-14 13:27:53 -07002229
Adam Cohen7d30a372013-07-01 17:03:59 -07002230 // Animate the drag view back to the original position
2231 void animateDragViewToOriginalPosition() {
2232 if (mDragView != null) {
2233 AnimatorSet anim = new AnimatorSet();
2234 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2235 anim.playTogether(
2236 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2237 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2238 anim.addListener(new AnimatorListenerAdapter() {
2239 @Override
2240 public void onAnimationEnd(Animator animation) {
2241 onPostReorderingAnimationCompleted();
2242 }
2243 });
2244 anim.start();
2245 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002246 }
2247
Adam Cohen7d30a372013-07-01 17:03:59 -07002248 // "Zooms out" the PagedView to reveal more side pages
2249 protected boolean zoomOut() {
2250 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2251 mZoomInOutAnim.cancel();
2252 }
2253
2254 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2255 mZoomInOutAnim = new AnimatorSet();
2256 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2257 mZoomInOutAnim.playTogether(
2258 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2259 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2260 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2261 @Override
2262 public void onAnimationStart(Animator animation) {
2263 // Show the delete drop target
2264 if (mDeleteDropTarget != null) {
2265 mDeleteDropTarget.setVisibility(View.VISIBLE);
2266 mDeleteDropTarget.animate().alpha(1f)
2267 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2268 .setListener(new AnimatorListenerAdapter() {
2269 @Override
2270 public void onAnimationStart(Animator animation) {
2271 mDeleteDropTarget.setAlpha(0f);
2272 }
2273 });
2274 }
2275 }
2276 });
2277 mZoomInOutAnim.start();
2278 return true;
2279 }
2280 return false;
2281 }
2282
2283 protected void onStartReordering() {
2284 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2285 mTouchState = TOUCH_STATE_REORDERING;
2286 mIsReordering = true;
2287
2288 // Mark all the non-widget pages as invisible
2289 getVisiblePages(mTempVisiblePagesRange);
2290 boundByReorderablePages(true, mTempVisiblePagesRange);
2291 for (int i = 0; i < getPageCount(); ++i) {
2292 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2293 getPageAt(i).setAlpha(0f);
2294 }
2295 }
2296
2297 // We must invalidate to trigger a redraw to update the layers such that the drag view
2298 // is always drawn on top
2299 invalidate();
2300 }
2301
2302 private void onPostReorderingAnimationCompleted() {
2303 // Trigger the callback when reordering has settled
2304 --mPostReorderingPreZoomInRemainingAnimationCount;
2305 if (mPostReorderingPreZoomInRunnable != null &&
2306 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2307 mPostReorderingPreZoomInRunnable.run();
2308 mPostReorderingPreZoomInRunnable = null;
2309 }
2310 }
2311
2312 protected void onEndReordering() {
2313 mIsReordering = false;
2314
2315 // Mark all the non-widget pages as visible again
2316 getVisiblePages(mTempVisiblePagesRange);
2317 boundByReorderablePages(true, mTempVisiblePagesRange);
2318 for (int i = 0; i < getPageCount(); ++i) {
2319 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2320 getPageAt(i).setAlpha(1f);
2321 }
2322 }
2323 }
2324
2325 public boolean startReordering() {
2326 int dragViewIndex = getPageNearestToCenterOfScreen();
2327 mTempVisiblePagesRange[0] = 0;
2328 mTempVisiblePagesRange[1] = getPageCount() - 1;
2329 boundByReorderablePages(true, mTempVisiblePagesRange);
2330 mReorderingStarted = true;
2331
2332 // Check if we are within the reordering range
2333 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2334 dragViewIndex <= mTempVisiblePagesRange[1]) {
2335 if (zoomOut()) {
2336 // Find the drag view under the pointer
2337 mDragView = getChildAt(dragViewIndex);
2338
2339 onStartReordering();
2340 }
2341 return true;
2342 }
2343 return false;
2344 }
2345
2346 boolean isReordering(boolean testTouchState) {
2347 boolean state = mIsReordering;
2348 if (testTouchState) {
2349 state &= (mTouchState == TOUCH_STATE_REORDERING);
2350 }
2351 return state;
2352 }
2353 void endReordering() {
2354 // For simplicity, we call endReordering sometimes even if reordering was never started.
2355 // In that case, we don't want to do anything.
2356 if (!mReorderingStarted) return;
2357 mReorderingStarted = false;
2358
2359 // If we haven't flung-to-delete the current child, then we just animate the drag view
2360 // back into position
2361 final Runnable onCompleteRunnable = new Runnable() {
2362 @Override
2363 public void run() {
2364 onEndReordering();
2365 }
2366 };
2367 if (!mDeferringForDelete) {
2368 mPostReorderingPreZoomInRunnable = new Runnable() {
2369 public void run() {
2370 zoomIn(onCompleteRunnable);
2371 };
2372 };
2373
2374 mPostReorderingPreZoomInRemainingAnimationCount =
2375 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2376 // Snap to the current page
2377 snapToPage(indexOfChild(mDragView), 0);
2378 // Animate the drag view back to the front position
2379 animateDragViewToOriginalPosition();
2380 } else {
2381 // Handled in post-delete-animation-callbacks
2382 }
2383 }
2384
2385 // "Zooms in" the PagedView to highlight the current page
2386 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2387 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2388 mZoomInOutAnim.cancel();
2389 }
2390 if (getScaleX() < 1f || getScaleY() < 1f) {
2391 mZoomInOutAnim = new AnimatorSet();
2392 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2393 mZoomInOutAnim.playTogether(
2394 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2395 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2396 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2397 @Override
2398 public void onAnimationStart(Animator animation) {
2399 // Hide the delete drop target
2400 if (mDeleteDropTarget != null) {
2401 mDeleteDropTarget.animate().alpha(0f)
2402 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2403 .setListener(new AnimatorListenerAdapter() {
2404 @Override
2405 public void onAnimationEnd(Animator animation) {
2406 mDeleteDropTarget.setVisibility(View.GONE);
2407 }
2408 });
2409 }
2410 }
2411 @Override
2412 public void onAnimationCancel(Animator animation) {
2413 mDragView = null;
2414 }
2415 @Override
2416 public void onAnimationEnd(Animator animation) {
2417 mDragView = null;
2418 if (onCompleteRunnable != null) {
2419 onCompleteRunnable.run();
2420 }
2421 }
2422 });
2423 mZoomInOutAnim.start();
2424 return true;
2425 } else {
2426 if (onCompleteRunnable != null) {
2427 onCompleteRunnable.run();
2428 }
2429 }
2430 return false;
2431 }
2432
2433 /*
2434 * Flinging to delete - IN PROGRESS
2435 */
2436 private PointF isFlingingToDelete() {
2437 ViewConfiguration config = ViewConfiguration.get(getContext());
2438 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2439
2440 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2441 // Do a quick dot product test to ensure that we are flinging upwards
2442 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2443 mVelocityTracker.getYVelocity());
2444 PointF upVec = new PointF(0f, -1f);
2445 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2446 (vel.length() * upVec.length()));
2447 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2448 return vel;
2449 }
2450 }
2451 return null;
2452 }
2453
2454 /**
2455 * Creates an animation from the current drag view along its current velocity vector.
2456 * For this animation, the alpha runs for a fixed duration and we update the position
2457 * progressively.
2458 */
2459 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2460 private View mDragView;
2461 private PointF mVelocity;
2462 private Rect mFrom;
2463 private long mPrevTime;
2464 private float mFriction;
2465
2466 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2467
2468 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2469 long startTime, float friction) {
2470 mDragView = dragView;
2471 mVelocity = vel;
2472 mFrom = from;
2473 mPrevTime = startTime;
2474 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2475 }
2476
2477 @Override
2478 public void onAnimationUpdate(ValueAnimator animation) {
2479 float t = ((Float) animation.getAnimatedValue()).floatValue();
2480 long curTime = AnimationUtils.currentAnimationTimeMillis();
2481
2482 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2483 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2484
2485 mDragView.setTranslationX(mFrom.left);
2486 mDragView.setTranslationY(mFrom.top);
2487 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2488
2489 mVelocity.x *= mFriction;
2490 mVelocity.y *= mFriction;
2491 mPrevTime = curTime;
2492 }
2493 };
2494
2495 private static final int ANIM_TAG_KEY = 100;
2496
2497 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2498 return new Runnable() {
2499 @Override
2500 public void run() {
2501 int dragViewIndex = indexOfChild(dragView);
2502
2503 // For each of the pages around the drag view, animate them from the previous
2504 // position to the new position in the layout (as a result of the drag view moving
2505 // in the layout)
2506 // NOTE: We can make an assumption here because we have side-bound pages that we
2507 // will always have pages to animate in from the left
2508 getVisiblePages(mTempVisiblePagesRange);
2509 boundByReorderablePages(true, mTempVisiblePagesRange);
2510 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2511 boolean slideFromLeft = (isLastWidgetPage ||
2512 dragViewIndex > mTempVisiblePagesRange[0]);
2513
2514 // Setup the scroll to the correct page before we swap the views
2515 if (slideFromLeft) {
2516 snapToPageImmediately(dragViewIndex - 1);
2517 }
2518
2519 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2520 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2521 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2522 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2523 ArrayList<Animator> animations = new ArrayList<Animator>();
2524 for (int i = lowerIndex; i <= upperIndex; ++i) {
2525 View v = getChildAt(i);
2526 // dragViewIndex < pageUnderPointIndex, so after we remove the
2527 // drag view all subsequent views to pageUnderPointIndex will
2528 // shift down.
2529 int oldX = 0;
2530 int newX = 0;
2531 if (slideFromLeft) {
2532 if (i == 0) {
2533 // Simulate the page being offscreen with the page spacing
2534 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2535 - mPageSpacing;
2536 } else {
2537 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2538 }
2539 newX = getViewportOffsetX() + getChildOffset(i);
2540 } else {
2541 oldX = getChildOffset(i) - getChildOffset(i - 1);
2542 newX = 0;
2543 }
2544
2545 // Animate the view translation from its old position to its new
2546 // position
2547 AnimatorSet anim = (AnimatorSet) v.getTag();
2548 if (anim != null) {
2549 anim.cancel();
2550 }
2551
2552 // Note: Hacky, but we want to skip any optimizations to not draw completely
2553 // hidden views
2554 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2555 v.setTranslationX(oldX - newX);
2556 anim = new AnimatorSet();
2557 anim.playTogether(
2558 ObjectAnimator.ofFloat(v, "translationX", 0f),
2559 ObjectAnimator.ofFloat(v, "alpha", 1f));
2560 animations.add(anim);
2561 v.setTag(ANIM_TAG_KEY, anim);
2562 }
2563
2564 AnimatorSet slideAnimations = new AnimatorSet();
2565 slideAnimations.playTogether(animations);
2566 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2567 slideAnimations.addListener(new AnimatorListenerAdapter() {
2568 @Override
2569 public void onAnimationEnd(Animator animation) {
2570 final Runnable onCompleteRunnable = new Runnable() {
2571 @Override
2572 public void run() {
2573 mDeferringForDelete = false;
2574 onEndReordering();
2575 onRemoveViewAnimationCompleted();
2576 }
2577 };
2578 zoomIn(onCompleteRunnable);
2579 }
2580 });
2581 slideAnimations.start();
2582
2583 removeView(dragView);
2584 onRemoveView(dragView, true);
2585 }
2586 };
2587 }
2588
2589 public void onFlingToDelete(PointF vel) {
2590 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2591
2592 // NOTE: Because it takes time for the first frame of animation to actually be
2593 // called and we expect the animation to be a continuation of the fling, we have
2594 // to account for the time that has elapsed since the fling finished. And since
2595 // we don't have a startDelay, we will always get call to update when we call
2596 // start() (which we want to ignore).
2597 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2598 private int mCount = -1;
2599 private long mStartTime;
2600 private float mOffset;
2601 /* Anonymous inner class ctor */ {
2602 mStartTime = startTime;
2603 }
2604
2605 @Override
2606 public float getInterpolation(float t) {
2607 if (mCount < 0) {
2608 mCount++;
2609 } else if (mCount == 0) {
2610 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2611 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2612 mCount++;
2613 }
2614 return Math.min(1f, mOffset + t);
2615 }
2616 };
2617
2618 final Rect from = new Rect();
2619 final View dragView = mDragView;
2620 from.left = (int) dragView.getTranslationX();
2621 from.top = (int) dragView.getTranslationY();
2622 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2623 from, startTime, FLING_TO_DELETE_FRICTION);
2624
2625 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2626
2627 // Create and start the animation
2628 ValueAnimator mDropAnim = new ValueAnimator();
2629 mDropAnim.setInterpolator(tInterpolator);
2630 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2631 mDropAnim.setFloatValues(0f, 1f);
2632 mDropAnim.addUpdateListener(updateCb);
2633 mDropAnim.addListener(new AnimatorListenerAdapter() {
2634 public void onAnimationEnd(Animator animation) {
2635 onAnimationEndRunnable.run();
2636 }
2637 });
2638 mDropAnim.start();
2639 mDeferringForDelete = true;
2640 }
2641
2642 /* Drag to delete */
2643 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2644 if (mDeleteDropTarget != null) {
2645 mAltTmpRect.set(0, 0, 0, 0);
2646 View parent = (View) mDeleteDropTarget.getParent();
2647 if (parent != null) {
2648 parent.getGlobalVisibleRect(mAltTmpRect);
2649 }
2650 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2651 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2652 return mTmpRect.contains(x, y);
2653 }
2654 return false;
2655 }
2656
2657 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2658
2659 private void onDropToDelete() {
2660 final View dragView = mDragView;
2661
2662 final float toScale = 0f;
2663 final float toAlpha = 0f;
2664
2665 // Create and start the complex animation
2666 ArrayList<Animator> animations = new ArrayList<Animator>();
2667 AnimatorSet motionAnim = new AnimatorSet();
2668 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2669 motionAnim.playTogether(
2670 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2671 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2672 animations.add(motionAnim);
2673
2674 AnimatorSet alphaAnim = new AnimatorSet();
2675 alphaAnim.setInterpolator(new LinearInterpolator());
2676 alphaAnim.playTogether(
2677 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2678 animations.add(alphaAnim);
2679
2680 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2681
2682 AnimatorSet anim = new AnimatorSet();
2683 anim.playTogether(animations);
2684 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2685 anim.addListener(new AnimatorListenerAdapter() {
2686 public void onAnimationEnd(Animator animation) {
2687 onAnimationEndRunnable.run();
2688 }
2689 });
2690 anim.start();
2691
2692 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002693 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002694
2695 /* Accessibility */
2696 @Override
2697 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2698 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002699 info.setScrollable(getPageCount() > 1);
2700 if (getCurrentPage() < getPageCount() - 1) {
2701 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2702 }
2703 if (getCurrentPage() > 0) {
2704 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2705 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002706 }
2707
2708 @Override
2709 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2710 super.onInitializeAccessibilityEvent(event);
2711 event.setScrollable(true);
2712 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2713 event.setFromIndex(mCurrentPage);
2714 event.setToIndex(mCurrentPage);
2715 event.setItemCount(getChildCount());
2716 }
2717 }
2718
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002719 @Override
2720 public boolean performAccessibilityAction(int action, Bundle arguments) {
2721 if (super.performAccessibilityAction(action, arguments)) {
2722 return true;
2723 }
2724 switch (action) {
2725 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2726 if (getCurrentPage() < getPageCount() - 1) {
2727 scrollRight();
2728 return true;
2729 }
2730 } break;
2731 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2732 if (getCurrentPage() > 0) {
2733 scrollLeft();
2734 return true;
2735 }
2736 } break;
2737 }
2738 return false;
2739 }
2740
Adam Cohen0ffac432013-07-10 11:19:26 -07002741 protected String getCurrentPageDescription() {
2742 return String.format(getContext().getString(R.string.default_scroll_format),
2743 getNextPage() + 1, getChildCount());
2744 }
2745
Winson Chungd11265e2011-08-30 13:37:23 -07002746 @Override
2747 public boolean onHoverEvent(android.view.MotionEvent event) {
2748 return true;
2749 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002750}