blob: 8027fa19c9e104cee4ca18bf1c086f1039aae811 [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 Cohenf698c6e2013-07-17 18:44:25 -0700107 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700108
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 Chung181c3dc2013-07-17 15:36:20 -0700499 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700500 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800501 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700502 }
503
Michael Jurka0142d492010-08-25 17:46:15 -0700504 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700505 if (mPageSwitchListener != null) {
506 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700507 }
Winson Chungd2be3812013-07-16 11:11:32 -0700508
509 // Update the page indicator (when we aren't reordering)
510 if (mPageIndicator != null && !isReordering(false)) {
511 mPageIndicator.setActiveMarker(getNextPage());
512 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700513 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800514 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700515 if (!mIsPageMoving) {
516 mIsPageMoving = true;
517 onPageBeginMoving();
518 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700519 }
520
Michael Jurkace7e05f2011-02-01 22:02:35 -0800521 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700522 if (mIsPageMoving) {
523 mIsPageMoving = false;
524 onPageEndMoving();
525 }
Michael Jurka0142d492010-08-25 17:46:15 -0700526 }
527
Adam Cohen26976d92011-03-22 15:33:33 -0700528 protected boolean isPageMoving() {
529 return mIsPageMoving;
530 }
531
Michael Jurka0142d492010-08-25 17:46:15 -0700532 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700533 protected void onPageBeginMoving() {
534 }
535
536 // a method that subclasses can override to add behavior
537 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700538 }
539
Winson Chung321e9ee2010-08-09 13:37:56 -0700540 /**
Winson Chung86f77532010-08-24 11:08:22 -0700541 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700542 *
543 * @param l The listener used to respond to long clicks.
544 */
545 @Override
546 public void setOnLongClickListener(OnLongClickListener l) {
547 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700548 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700549 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700550 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700551 }
552 }
553
554 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800555 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700556 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800557 }
558
559 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700560 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700561 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800562 mUnboundedScrollX = x;
563
Adam Cohen0ffac432013-07-10 11:19:26 -0700564 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
565 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
566 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800567 super.scrollTo(0, y);
568 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700569 if (isRtl) {
570 overScroll(x - mMaxScrollX);
571 } else {
572 overScroll(x);
573 }
Adam Cohen68d73932010-11-15 10:50:58 -0800574 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700575 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800576 super.scrollTo(mMaxScrollX, y);
577 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700578 if (isRtl) {
579 overScroll(x);
580 } else {
581 overScroll(x - mMaxScrollX);
582 }
Adam Cohen68d73932010-11-15 10:50:58 -0800583 }
584 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800585 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800586 super.scrollTo(x, y);
587 }
588
Michael Jurka0142d492010-08-25 17:46:15 -0700589 mTouchX = x;
590 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700591
592 // Update the last motion events when scrolling
593 if (isReordering(true)) {
594 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
595 mLastMotionX = p[0];
596 mLastMotionY = p[1];
597 updateDragViewTranslationDuringDrag();
598 }
Michael Jurka0142d492010-08-25 17:46:15 -0700599 }
600
601 // we moved this functionality to a helper function so SmoothPagedView can reuse it
602 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700603 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700604 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700605 if (getScrollX() != mScroller.getCurrX()
606 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700607 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700608 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
609 }
Michael Jurka0142d492010-08-25 17:46:15 -0700610 invalidate();
611 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700612 } else if (mNextPage != INVALID_PAGE) {
613 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700614 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700615 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700616
Adam Cohen73aa9752010-11-24 16:26:58 -0800617 // We don't want to trigger a page end moving unless the page has settled
618 // and the user has stopped scrolling
619 if (mTouchState == TOUCH_STATE_REST) {
620 pageEndMoving();
621 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700622
Adam Cohen7d30a372013-07-01 17:03:59 -0700623 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700624 // Notify the user when the page changes
625 AccessibilityManager accessibilityManager = (AccessibilityManager)
626 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
627 if (accessibilityManager.isEnabled()) {
628 AccessibilityEvent ev =
629 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
630 ev.getText().add(getCurrentPageDescription());
631 sendAccessibilityEventUnchecked(ev);
632 }
Michael Jurka0142d492010-08-25 17:46:15 -0700633 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700634 }
Michael Jurka0142d492010-08-25 17:46:15 -0700635 return false;
636 }
637
638 @Override
639 public void computeScroll() {
640 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700641 }
642
Adam Cohen7d30a372013-07-01 17:03:59 -0700643 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
644 return mTopAlignPageWhenShrinkingForBouncer;
645 }
646
Adam Cohen96d30a12013-07-16 18:13:21 -0700647 public static class LayoutParams extends ViewGroup.LayoutParams {
648 public boolean isFullScreenPage = false;
649
650 /**
651 * {@inheritDoc}
652 */
653 public LayoutParams(int width, int height) {
654 super(width, height);
655 }
656
657 public LayoutParams(ViewGroup.LayoutParams source) {
658 super(source);
659 }
660 }
661
662 protected LayoutParams generateDefaultLayoutParams() {
663 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
664 }
665
666 public void addFullScreenPage(View page, int width, int height) {
667 LayoutParams lp = generateDefaultLayoutParams();
668 lp.isFullScreenPage = true;
669 super.addView(page, 0, lp);
670 }
671
Winson Chung321e9ee2010-08-09 13:37:56 -0700672 @Override
673 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700674 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700675 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
676 return;
677 }
678
Adam Cohen7d30a372013-07-01 17:03:59 -0700679 // We measure the dimensions of the PagedView to be larger than the pages so that when we
680 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700681 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
682 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
683 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700684 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700685 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
686 // viewport, we can be at most one and a half screens offset once we scale down
687 DisplayMetrics dm = getResources().getDisplayMetrics();
688 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
689 int parentWidthSize = (int) (1.5f * maxSize);
690 int parentHeightSize = maxSize;
691 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
692 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
693 mViewport.set(0, 0, widthSize, heightSize);
694
695 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
696 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
697 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700698 }
699
Winson Chung8aad6102012-05-11 16:27:49 -0700700 // Return early if we aren't given a proper dimension
701 if (widthSize <= 0 || heightSize <= 0) {
702 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
703 return;
704 }
705
Adam Lesinski6b879f02010-11-04 16:15:23 -0700706 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
707 * of the All apps view on XLarge displays to not take up more space then it needs. Width
708 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
709 * each page to have the same width.
710 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700711 final int verticalPadding = getPaddingTop() + getPaddingBottom();
712 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700713
714 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700715 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700716 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700717 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
718 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
719 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
720 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700721 final int childCount = getChildCount();
722 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700723 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700724 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700725 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
726
727 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700728 int childHeightMode;
729 int childWidth;
730 int childHeight;
731
732 if (!lp.isFullScreenPage) {
733 if (lp.width == LayoutParams.WRAP_CONTENT) {
734 childWidthMode = MeasureSpec.AT_MOST;
735 } else {
736 childWidthMode = MeasureSpec.EXACTLY;
737 }
738
739 if (lp.height == LayoutParams.WRAP_CONTENT) {
740 childHeightMode = MeasureSpec.AT_MOST;
741 } else {
742 childHeightMode = MeasureSpec.EXACTLY;
743 }
744
745 childWidth = widthSize - horizontalPadding;
746 childHeight = heightSize - verticalPadding;
747
Michael Jurka5f1c5092010-09-03 14:15:02 -0700748 } else {
749 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700750 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700751
752 childWidth = getViewportWidth();
753 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700754 }
755
756 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700757 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
758 final int childHeightMeasureSpec =
759 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700760 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700761 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700762 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700763
Winson Chung8aad6102012-05-11 16:27:49 -0700764 // We can't call getChildOffset/getRelativeChildOffset until we set the measured dimensions.
765 // We also wait until we set the measured dimensions before flushing the cache as well, to
766 // ensure that the cache is filled with good values.
767 invalidateCachedOffsets();
768
Winson Chunga128a7b2012-04-30 15:23:15 -0700769 if (childCount > 0) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700770 if (DEBUG) Log.d(TAG, "getRelativeChildOffset(): " + getViewportWidth() + ", "
Winson Chunga128a7b2012-04-30 15:23:15 -0700771 + getChildWidth(0));
772
773 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700774 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700775 // The gap between pages in the PagedView should be equal to the gap from the page
776 // to the edge of the screen (so it is not visible in the current screen). To
777 // account for unequal padding on each side of the paged view, we take the maximum
778 // of the left/right gap and use that as the gap between each page.
779 int offset = getRelativeChildOffset(0);
780 int spacing = Math.max(offset, widthSize - offset -
781 getChildAt(0).getMeasuredWidth());
782 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700783 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700784 }
785 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700786 }
787
Adam Cohen60b07122011-11-14 17:26:06 -0800788 public void setPageSpacing(int pageSpacing) {
789 mPageSpacing = pageSpacing;
790 invalidateCachedOffsets();
791 }
792
Winson Chung321e9ee2010-08-09 13:37:56 -0700793 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700794 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700795 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700796 return;
797 }
798
Winson Chung785d2eb2011-04-14 16:08:02 -0700799 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700800 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700801
Adam Cohen7d30a372013-07-01 17:03:59 -0700802 int offsetX = getViewportOffsetX();
803 int offsetY = getViewportOffsetY();
804
805 // Update the viewport offsets
806 mViewport.offset(offsetX, offsetY);
807
Adam Cohen0ffac432013-07-10 11:19:26 -0700808 final boolean isRtl = isLayoutRtl();
809
810 final int startIndex = isRtl ? childCount - 1 : 0;
811 final int endIndex = isRtl ? -1 : childCount;
812 final int delta = isRtl ? -1 : 1;
813
Adam Cohen7d30a372013-07-01 17:03:59 -0700814 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohen0ffac432013-07-10 11:19:26 -0700815 int childLeft = offsetX + getRelativeChildOffset(startIndex);
816 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700817 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700818 LayoutParams lp = (LayoutParams) child.getLayoutParams();
819 int childTop;
820
821 if (lp.isFullScreenPage) {
822 childTop = offsetY;
823 } else {
824 childTop = offsetY + getPaddingTop();
825 if (mCenterPagesVertically) {
826 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
827 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700828 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700829
Winson Chung321e9ee2010-08-09 13:37:56 -0700830 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700831 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700832 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800833
Winson Chung785d2eb2011-04-14 16:08:02 -0700834 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700835 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800836 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700837 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700838 }
839 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700840
841 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
842 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800843 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700844 setHorizontalScrollBarEnabled(true);
845 mFirstLayout = false;
846 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700847
848 if (childCount > 0) {
849 final int index = isLayoutRtl() ? 0 : childCount - 1;
850 mMaxScrollX = getChildOffset(index) - getRelativeChildOffset(index);
851 } else {
852 mMaxScrollX = 0;
853 }
854
855 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
856 !mDeferringForDelete) {
857 setCurrentPage(getNextPage());
858 }
859 mChildCountOnLastLayout = getChildCount();
Winson Chunge3193b92010-09-10 11:44:42 -0700860 }
861
Adam Cohenf34bab52010-09-30 14:11:56 -0700862 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700863 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
864
865 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700866 for (int i = 0; i < getChildCount(); i++) {
867 View child = getChildAt(i);
868 if (child != null) {
869 float scrollProgress = getScrollProgress(screenCenter, child, i);
870 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800871 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700872 }
873 }
874 invalidate();
875 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700876 }
877
Winson Chunge3193b92010-09-10 11:44:42 -0700878 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700879 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700880 // Update the page indicator, we don't update the page indicator as we
881 // add/remove pages
882 if (mPageIndicator != null && !isReordering(false)) {
883 mPageIndicator.addMarker(indexOfChild(child));
884 }
885
Adam Cohen2591f6a2011-10-25 14:36:40 -0700886 // This ensures that when children are added, they get the correct transforms / alphas
887 // in accordance with any scroll effects.
888 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700889 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700890
Adam Cohen2591f6a2011-10-25 14:36:40 -0700891 invalidate();
Adam Cohen25b29952011-11-02 14:49:06 -0700892 invalidateCachedOffsets();
Adam Cohen2591f6a2011-10-25 14:36:40 -0700893 }
894
Michael Jurka8b805b12012-04-18 14:23:14 -0700895 @Override
896 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700897 mForceScreenScrolled = true;
898 invalidate();
899 invalidateCachedOffsets();
Michael Jurka8b805b12012-04-18 14:23:14 -0700900 }
901
Winson Chungd2be3812013-07-16 11:11:32 -0700902 private void removeMarkerForView(int index) {
903 // Update the page indicator, we don't update the page indicator as we
904 // add/remove pages
905 if (mPageIndicator != null && !isReordering(false)) {
906 mPageIndicator.removeMarker(index);
907 }
908 }
909
910 @Override
911 public void removeView(View v) {
912 // XXX: We should find a better way to hook into this before the view
913 // gets removed form its parent...
914 removeMarkerForView(indexOfChild(v));
915 super.removeView(v);
916 }
917 @Override
918 public void removeViewInLayout(View v) {
919 // XXX: We should find a better way to hook into this before the view
920 // gets removed form its parent...
921 removeMarkerForView(indexOfChild(v));
922 super.removeViewInLayout(v);
923 }
924 @Override
925 public void removeViewAt(int index) {
926 // XXX: We should find a better way to hook into this before the view
927 // gets removed form its parent...
928 removeViewAt(index);
929 super.removeViewAt(index);
930 }
931 @Override
932 public void removeAllViewsInLayout() {
933 // Update the page indicator, we don't update the page indicator as we
934 // add/remove pages
935 if (mPageIndicator != null) {
936 mPageIndicator.removeAllMarkers();
937 }
938
939 super.removeAllViewsInLayout();
940 }
941
Adam Cohen73894962011-10-31 13:17:17 -0700942 protected void invalidateCachedOffsets() {
943 int count = getChildCount();
Adam Cohen25b29952011-11-02 14:49:06 -0700944 if (count == 0) {
Adam Cohen25b29952011-11-02 14:49:06 -0700945 mChildRelativeOffsets = null;
Adam Cohen25b29952011-11-02 14:49:06 -0700946 return;
947 }
Adam Cohen73894962011-10-31 13:17:17 -0700948
Adam Cohen73894962011-10-31 13:17:17 -0700949 mChildRelativeOffsets = new int[count];
Adam Cohen73894962011-10-31 13:17:17 -0700950 for (int i = 0; i < count; i++) {
Adam Cohen73894962011-10-31 13:17:17 -0700951 mChildRelativeOffsets[i] = -1;
Adam Cohen73894962011-10-31 13:17:17 -0700952 }
953 }
954
955 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700956 if (index < 0 || index > getChildCount() - 1) return 0;
957
Adam Cohen0ffac432013-07-10 11:19:26 -0700958 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700959
Adam Cohenf698c6e2013-07-17 18:44:25 -0700960 if (isRtl) index = getChildCount() - index - 1;
961 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -0700962
Adam Cohenf698c6e2013-07-17 18:44:25 -0700963 return offset;
Adam Cohen73894962011-10-31 13:17:17 -0700964 }
965
966 protected int getRelativeChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700967 if (index < 0 || index > getChildCount() - 1) return 0;
968
Adam Cohen73894962011-10-31 13:17:17 -0700969 if (mChildRelativeOffsets != null && mChildRelativeOffsets[index] != -1) {
970 return mChildRelativeOffsets[index];
971 } else {
Michael Jurka8b805b12012-04-18 14:23:14 -0700972 final int padding = getPaddingLeft() + getPaddingRight();
973 final int offset = getPaddingLeft() +
Adam Cohen7d30a372013-07-01 17:03:59 -0700974 (getViewportWidth() - padding - getChildWidth(index)) / 2;
Adam Cohen73894962011-10-31 13:17:17 -0700975 if (mChildRelativeOffsets != null) {
976 mChildRelativeOffsets[index] = offset;
977 }
978 return offset;
979 }
980 }
981
Adam Cohen7d30a372013-07-01 17:03:59 -0700982 void boundByReorderablePages(boolean isReordering, int[] range) {
983 // Do nothing
984 }
985
986 // TODO: Fix this
Michael Jurkadde558b2011-11-09 22:09:06 -0800987 protected void getVisiblePages(int[] range) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700988 range[0] = 0;
989 range[1] = getPageCount() - 1;
990
991 /*
Michael Jurka0142d492010-08-25 17:46:15 -0700992 final int pageCount = getChildCount();
Michael Jurka4ff7d792012-04-02 03:46:50 -0700993
Michael Jurkac4fb9172010-09-02 17:19:20 -0700994 if (pageCount > 0) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700995 final int screenWidth = getViewportWidth();
996 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -0700997 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -0700998 int offsetX = getViewportOffsetX() + getScrollX();
Michael Jurka47f74742012-03-02 13:39:13 -0800999 View currPage = getPageAt(leftScreen);
Adam Cohen7d30a372013-07-01 17:03:59 -07001000 while (leftScreen < pageCount - 1 &&
Michael Jurka8b805b12012-04-18 14:23:14 -07001001 currPage.getX() + currPage.getWidth() -
Adam Cohen7d30a372013-07-01 17:03:59 -07001002 currPage.getPaddingRight() < offsetX) {
1003 leftScreen++;
Michael Jurka47f74742012-03-02 13:39:13 -08001004 currPage = getPageAt(leftScreen);
Michael Jurkac4fb9172010-09-02 17:19:20 -07001005 }
1006 rightScreen = leftScreen;
Adam Cohen7d30a372013-07-01 17:03:59 -07001007 currPage = getPageAt(rightScreen + 1);
1008 while (rightScreen < pageCount - 1 &&
1009 currPage.getX() - currPage.getPaddingLeft() < offsetX + screenWidth) {
1010 rightScreen++;
1011 currPage = getPageAt(rightScreen + 1);
Michael Jurkac4fb9172010-09-02 17:19:20 -07001012 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001013
1014 // TEMP: this is a hacky way to ensure that animations to new pages are not clipped
1015 // because we don't draw them while scrolling?
1016 range[0] = Math.max(0, leftScreen - 1);
1017 range[1] = Math.min(rightScreen + 1, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001018 } else {
1019 range[0] = -1;
1020 range[1] = -1;
1021 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001022 */
Michael Jurkadde558b2011-11-09 22:09:06 -08001023 }
1024
Michael Jurka920d7f42012-05-14 16:29:55 -07001025 protected boolean shouldDrawChild(View child) {
1026 return child.getAlpha() > 0;
1027 }
1028
Michael Jurkadde558b2011-11-09 22:09:06 -08001029 @Override
1030 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001031 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001032 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1033 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001034 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001035
1036 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001037 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1038 // set it for the next frame
1039 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001040 screenScrolled(screenCenter);
1041 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001042 }
1043
1044 // Find out which screens are visible; as an optimization we only call draw on them
1045 final int pageCount = getChildCount();
1046 if (pageCount > 0) {
1047 getVisiblePages(mTempVisiblePagesRange);
1048 final int leftScreen = mTempVisiblePagesRange[0];
1049 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001050 if (leftScreen != -1 && rightScreen != -1) {
1051 final long drawingTime = getDrawingTime();
1052 // Clip to the bounds
1053 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001054 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1055 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001056
Adam Cohen7d30a372013-07-01 17:03:59 -07001057 // Draw all the children, leaving the drag view for last
1058 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001059 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001060 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001061 if (mForceDrawAllChildrenNextFrame ||
1062 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001063 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001064 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001065 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001066 // Draw the drag view on top (if there is one)
1067 if (mDragView != null) {
1068 drawChild(canvas, mDragView, drawingTime);
1069 }
1070
Michael Jurka5e368ff2012-05-14 23:13:15 -07001071 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001072 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001073 }
Michael Jurka0142d492010-08-25 17:46:15 -07001074 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001075 }
1076
1077 @Override
1078 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001079 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001080 if (page != mCurrentPage || !mScroller.isFinished()) {
1081 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001082 return true;
1083 }
1084 return false;
1085 }
1086
1087 @Override
1088 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001089 int focusablePage;
1090 if (mNextPage != INVALID_PAGE) {
1091 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001092 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001093 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001094 }
Winson Chung86f77532010-08-24 11:08:22 -07001095 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001096 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001097 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001098 }
1099 return false;
1100 }
1101
1102 @Override
1103 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001104 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001105 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001106 if (getCurrentPage() > 0) {
1107 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001108 return true;
1109 }
1110 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001111 if (getCurrentPage() < getPageCount() - 1) {
1112 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001113 return true;
1114 }
1115 }
1116 return super.dispatchUnhandledMove(focused, direction);
1117 }
1118
1119 @Override
1120 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001121 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001122 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001123 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001124 }
1125 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001126 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001127 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001128 }
1129 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001130 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001131 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001132 }
1133 }
1134 }
1135
1136 /**
1137 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001138 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001139 *
Winson Chung86f77532010-08-24 11:08:22 -07001140 * This happens when live folders requery, and if they're off page, they
1141 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001142 */
1143 @Override
1144 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001145 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001146 View v = focused;
1147 while (true) {
1148 if (v == current) {
1149 super.focusableViewAvailable(focused);
1150 return;
1151 }
1152 if (v == this) {
1153 return;
1154 }
1155 ViewParent parent = v.getParent();
1156 if (parent instanceof View) {
1157 v = (View)v.getParent();
1158 } else {
1159 return;
1160 }
1161 }
1162 }
1163
1164 /**
1165 * {@inheritDoc}
1166 */
1167 @Override
1168 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1169 if (disallowIntercept) {
1170 // We need to make sure to cancel our long press if
1171 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001172 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001173 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001174 }
1175 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1176 }
1177
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001178 /**
1179 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1180 */
1181 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001182 if (isLayoutRtl()) {
1183 return (x > (getViewportOffsetX() + getViewportWidth() -
1184 getRelativeChildOffset(mCurrentPage) + mPageSpacing));
1185 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001186 return (x < getViewportOffsetX() + getRelativeChildOffset(mCurrentPage) - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001187 }
1188
1189 /**
1190 * Return true if a tap at (x, y) should trigger a flip to the next page.
1191 */
1192 protected boolean hitsNextPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001193 if (isLayoutRtl()) {
1194 return (x < getViewportOffsetX() + getRelativeChildOffset(mCurrentPage) - mPageSpacing);
1195 }
1196 return (x > (getViewportOffsetX() + getViewportWidth() -
1197 getRelativeChildOffset(mCurrentPage) + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001198 }
Winson Chung52aee602013-01-30 12:01:02 -08001199
Adam Cohen7d30a372013-07-01 17:03:59 -07001200 /** Returns whether x and y originated within the buffered viewport */
1201 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1202 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1203 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1204 return mTmpRect.contains(x, y);
1205 }
1206
1207 /** Returns whether x and y originated within the current page view bounds */
1208 private boolean isTouchPointInCurrentPage(int x, int y) {
1209 View v = getPageAt(getCurrentPage());
1210 if (v != null) {
1211 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1212 v.getBottom());
1213 return mTmpRect.contains(x, y);
1214 }
1215 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001216 }
1217
Winson Chung321e9ee2010-08-09 13:37:56 -07001218 @Override
1219 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001220 if (DISABLE_TOUCH_INTERACTION) {
1221 return false;
1222 }
1223
Winson Chung321e9ee2010-08-09 13:37:56 -07001224 /*
1225 * This method JUST determines whether we want to intercept the motion.
1226 * If we return true, onTouchEvent will be called and we do the actual
1227 * scrolling there.
1228 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001229 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001230
Winson Chung45e1d6e2010-11-09 17:19:49 -08001231 // Skip touch handling if there are no pages to swipe
1232 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1233
Winson Chung321e9ee2010-08-09 13:37:56 -07001234 /*
1235 * Shortcut the most recurring case: the user is in the dragging
1236 * state and he is moving his finger. We want to intercept this
1237 * motion.
1238 */
1239 final int action = ev.getAction();
1240 if ((action == MotionEvent.ACTION_MOVE) &&
1241 (mTouchState == TOUCH_STATE_SCROLLING)) {
1242 return true;
1243 }
1244
Winson Chung321e9ee2010-08-09 13:37:56 -07001245 switch (action & MotionEvent.ACTION_MASK) {
1246 case MotionEvent.ACTION_MOVE: {
1247 /*
1248 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1249 * whether the user has moved far enough from his original down touch.
1250 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001251 if (mActivePointerId != INVALID_POINTER) {
1252 determineScrollingStart(ev);
1253 break;
1254 }
1255 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1256 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1257 // i.e. fall through to the next case (don't break)
1258 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1259 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001260 }
1261
1262 case MotionEvent.ACTION_DOWN: {
1263 final float x = ev.getX();
1264 final float y = ev.getY();
1265 // Remember location of down touch
1266 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001267 mDownMotionY = y;
1268 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001269 mLastMotionX = x;
1270 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001271 float[] p = mapPointFromViewToParent(this, x, y);
1272 mParentDownMotionX = p[0];
1273 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001274 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001275 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001276 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001277
1278 // Determine if the down event is within the threshold to be an edge swipe
1279 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1280 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1281 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1282 mDownEventOnEdge = true;
1283 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001284
1285 /*
1286 * If being flinged and user touches the screen, initiate drag;
1287 * otherwise don't. mScroller.isFinished should be false when
1288 * being flinged.
1289 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001290 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001291 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1292 if (finishedScrolling) {
1293 mTouchState = TOUCH_STATE_REST;
1294 mScroller.abortAnimation();
1295 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001296 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1297 mTouchState = TOUCH_STATE_SCROLLING;
1298 } else {
1299 mTouchState = TOUCH_STATE_REST;
1300 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001301 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001302
Winson Chung86f77532010-08-24 11:08:22 -07001303 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001304 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001305 if (!DISABLE_TOUCH_SIDE_PAGES) {
1306 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1307 if (getChildCount() > 0) {
1308 if (hitsPreviousPage(x, y)) {
1309 mTouchState = TOUCH_STATE_PREV_PAGE;
1310 } else if (hitsNextPage(x, y)) {
1311 mTouchState = TOUCH_STATE_NEXT_PAGE;
1312 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001313 }
1314 }
1315 }
1316 break;
1317 }
1318
Winson Chung321e9ee2010-08-09 13:37:56 -07001319 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001320 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001321 resetTouchState();
1322 // Just intercept the touch event on up if we tap outside the strict viewport
1323 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1324 return true;
1325 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001326 break;
1327
1328 case MotionEvent.ACTION_POINTER_UP:
1329 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001330 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001331 break;
1332 }
1333
1334 /*
1335 * The only time we want to intercept motion events is if we are in the
1336 * drag mode.
1337 */
1338 return mTouchState != TOUCH_STATE_REST;
1339 }
1340
Adam Cohenf8d28232011-02-01 21:47:00 -08001341 protected void determineScrollingStart(MotionEvent ev) {
1342 determineScrollingStart(ev, 1.0f);
1343 }
1344
Winson Chung321e9ee2010-08-09 13:37:56 -07001345 /*
1346 * Determines if we should change the touch state to start scrolling after the
1347 * user moves their touch point too far.
1348 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001349 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001350 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001351 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001352 if (pointerIndex == -1) return;
1353
1354 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001355 final float x = ev.getX(pointerIndex);
1356 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001357 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1358
1359 // If we're only allowing edge swipes, we break out early if the down event wasn't
1360 // at the edge.
1361 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1362
Winson Chung321e9ee2010-08-09 13:37:56 -07001363 final int xDiff = (int) Math.abs(x - mLastMotionX);
1364 final int yDiff = (int) Math.abs(y - mLastMotionY);
1365
Adam Cohenf8d28232011-02-01 21:47:00 -08001366 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001367 boolean xPaged = xDiff > mPagingTouchSlop;
1368 boolean xMoved = xDiff > touchSlop;
1369 boolean yMoved = yDiff > touchSlop;
1370
Adam Cohenf8d28232011-02-01 21:47:00 -08001371 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001372 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001373 // Scroll if the user moved far enough along the X axis
1374 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001375 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001376 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001377 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001378 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001379 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1380 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001381 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001382 }
1383 }
1384
Adam Cohen7d30a372013-07-01 17:03:59 -07001385 protected float getMaxScrollProgress() {
1386 return 1.0f;
1387 }
1388
Adam Cohenf8d28232011-02-01 21:47:00 -08001389 protected void cancelCurrentPageLongPress() {
1390 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001391 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001392 // Try canceling the long press. It could also have been scheduled
1393 // by a distant descendant, so use the mAllowLongPress flag to block
1394 // everything
1395 final View currentPage = getPageAt(mCurrentPage);
1396 if (currentPage != null) {
1397 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001398 }
1399 }
1400 }
1401
Adam Cohen7d30a372013-07-01 17:03:59 -07001402 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1403 final int halfScreenSize = getViewportWidth() / 2;
1404
1405 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1406 screenCenter = Math.max(halfScreenSize, screenCenter);
1407
1408 return getScrollProgress(screenCenter, v, page);
1409 }
1410
Adam Cohenb5ba0972011-09-07 18:02:31 -07001411 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001412 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001413
Adam Cohen96d30a12013-07-16 18:13:21 -07001414 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001415 int delta = screenCenter - (getChildOffset(page) -
1416 getRelativeChildOffset(page) + halfScreenSize);
1417
1418 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001419 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1420 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001421 return scrollProgress;
1422 }
1423
Adam Cohene0f66b52010-11-23 15:06:07 -08001424 // This curve determines how the effect of scrolling over the limits of the page dimishes
1425 // as the user pulls further and further from the bounds
1426 private float overScrollInfluenceCurve(float f) {
1427 f -= 1.0f;
1428 return f * f * f + 1.0f;
1429 }
1430
Adam Cohenb5ba0972011-09-07 18:02:31 -07001431 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001432 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001433
1434 // We want to reach the max over scroll effect when the user has
1435 // over scrolled half the size of the screen
1436 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1437
1438 if (f == 0) return;
1439
1440 // Clamp this factor, f, to -1 < f < 1
1441 if (Math.abs(f) >= 1) {
1442 f /= Math.abs(f);
1443 }
1444
1445 int overScrollAmount = (int) Math.round(f * screenSize);
1446 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001447 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001448 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001449 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001450 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001451 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001452 }
1453 invalidate();
1454 }
1455
1456 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001457 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001458
1459 float f = (amount / screenSize);
1460
1461 if (f == 0) return;
1462 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1463
Adam Cohen7bfc9792011-01-28 13:52:37 -08001464 // Clamp this factor, f, to -1 < f < 1
1465 if (Math.abs(f) >= 1) {
1466 f /= Math.abs(f);
1467 }
1468
Adam Cohene0f66b52010-11-23 15:06:07 -08001469 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001470 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001471 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001472 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001473 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001474 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001475 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001476 }
1477 invalidate();
1478 }
1479
Adam Cohenb5ba0972011-09-07 18:02:31 -07001480 protected void overScroll(float amount) {
1481 dampedOverScroll(amount);
1482 }
1483
Michael Jurkac5b262c2011-01-12 20:24:50 -08001484 protected float maxOverScroll() {
1485 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001486 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001487 float f = 1.0f;
1488 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1489 return OVERSCROLL_DAMP_FACTOR * f;
1490 }
1491
Winson Chung321e9ee2010-08-09 13:37:56 -07001492 @Override
1493 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001494 if (DISABLE_TOUCH_INTERACTION) {
1495 return false;
1496 }
1497
Winson Chung45e1d6e2010-11-09 17:19:49 -08001498 // Skip touch handling if there are no pages to swipe
1499 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1500
Michael Jurkab8f06722010-10-10 15:58:46 -07001501 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001502
1503 final int action = ev.getAction();
1504
1505 switch (action & MotionEvent.ACTION_MASK) {
1506 case MotionEvent.ACTION_DOWN:
1507 /*
1508 * If being flinged and user touches, stop the fling. isFinished
1509 * will be false if being flinged.
1510 */
1511 if (!mScroller.isFinished()) {
1512 mScroller.abortAnimation();
1513 }
1514
1515 // Remember where the motion event started
1516 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001517 mDownMotionY = mLastMotionY = ev.getY();
1518 mDownScrollX = getScrollX();
1519 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1520 mParentDownMotionX = p[0];
1521 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001522 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001523 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001524 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001525
1526 // Determine if the down event is within the threshold to be an edge swipe
1527 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1528 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1529 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1530 mDownEventOnEdge = true;
1531 }
1532
Michael Jurka0142d492010-08-25 17:46:15 -07001533 if (mTouchState == TOUCH_STATE_SCROLLING) {
1534 pageBeginMoving();
1535 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001536 break;
1537
1538 case MotionEvent.ACTION_MOVE:
1539 if (mTouchState == TOUCH_STATE_SCROLLING) {
1540 // Scroll to follow the motion event
1541 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001542
1543 if (pointerIndex == -1) return true;
1544
Winson Chung321e9ee2010-08-09 13:37:56 -07001545 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001546 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001547
Adam Cohenaefd4e12011-02-14 16:39:38 -08001548 mTotalMotionX += Math.abs(deltaX);
1549
Winson Chungc0844aa2011-02-02 15:25:58 -08001550 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1551 // keep the remainder because we are actually testing if we've moved from the last
1552 // scrolled position (which is discrete).
1553 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001554 mTouchX += deltaX;
1555 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1556 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001557 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001558 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001559 } else {
1560 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001561 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001562 mLastMotionX = x;
1563 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001564 } else {
1565 awakenScrollBars();
1566 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001567 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1568 // Update the last motion position
1569 mLastMotionX = ev.getX();
1570 mLastMotionY = ev.getY();
1571
1572 // Update the parent down so that our zoom animations take this new movement into
1573 // account
1574 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1575 mParentDownMotionX = pt[0];
1576 mParentDownMotionY = pt[1];
1577 updateDragViewTranslationDuringDrag();
1578
1579 // Find the closest page to the touch point
1580 final int dragViewIndex = indexOfChild(mDragView);
1581 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1582 getViewportWidth());
1583 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1584 + bufferSize);
1585 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1586 - bufferSize);
1587
1588 // Change the drag view if we are hovering over the drop target
1589 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1590 (int) mParentDownMotionX, (int) mParentDownMotionY);
1591 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1592
1593 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1594 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1595 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1596 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1597 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1598 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1599
1600 float parentX = mParentDownMotionX;
1601 int pageIndexToSnapTo = -1;
1602 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1603 pageIndexToSnapTo = dragViewIndex - 1;
1604 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1605 pageIndexToSnapTo = dragViewIndex + 1;
1606 }
1607
1608 final int pageUnderPointIndex = pageIndexToSnapTo;
1609 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1610 mTempVisiblePagesRange[0] = 0;
1611 mTempVisiblePagesRange[1] = getPageCount() - 1;
1612 boundByReorderablePages(true, mTempVisiblePagesRange);
1613 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1614 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1615 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1616 mSidePageHoverIndex = pageUnderPointIndex;
1617 mSidePageHoverRunnable = new Runnable() {
1618 @Override
1619 public void run() {
1620 // Update the down scroll position to account for the fact that the
1621 // current page is moved
1622 mDownScrollX = getChildOffset(pageUnderPointIndex)
1623 - getRelativeChildOffset(pageUnderPointIndex);
1624
1625 // Setup the scroll to the correct page before we swap the views
1626 snapToPage(pageUnderPointIndex);
1627
1628 // For each of the pages between the paged view and the drag view,
1629 // animate them from the previous position to the new position in
1630 // the layout (as a result of the drag view moving in the layout)
1631 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1632 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1633 dragViewIndex + 1 : pageUnderPointIndex;
1634 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1635 dragViewIndex - 1 : pageUnderPointIndex;
1636 for (int i = lowerIndex; i <= upperIndex; ++i) {
1637 View v = getChildAt(i);
1638 // dragViewIndex < pageUnderPointIndex, so after we remove the
1639 // drag view all subsequent views to pageUnderPointIndex will
1640 // shift down.
1641 int oldX = getViewportOffsetX() + getChildOffset(i);
1642 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1643
1644 // Animate the view translation from its old position to its new
1645 // position
1646 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1647 if (anim != null) {
1648 anim.cancel();
1649 }
1650
1651 v.setTranslationX(oldX - newX);
1652 anim = new AnimatorSet();
1653 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1654 anim.playTogether(
1655 ObjectAnimator.ofFloat(v, "translationX", 0f));
1656 anim.start();
1657 v.setTag(anim);
1658 }
1659
1660 removeView(mDragView);
1661 onRemoveView(mDragView, false);
1662 addView(mDragView, pageUnderPointIndex);
1663 onAddView(mDragView, pageUnderPointIndex);
1664 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001665 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001666 }
1667 };
1668 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1669 }
1670 } else {
1671 removeCallbacks(mSidePageHoverRunnable);
1672 mSidePageHoverIndex = -1;
1673 }
Adam Cohen564976a2010-10-13 18:52:07 -07001674 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001675 determineScrollingStart(ev);
1676 }
1677 break;
1678
1679 case MotionEvent.ACTION_UP:
1680 if (mTouchState == TOUCH_STATE_SCROLLING) {
1681 final int activePointerId = mActivePointerId;
1682 final int pointerIndex = ev.findPointerIndex(activePointerId);
1683 final float x = ev.getX(pointerIndex);
1684 final VelocityTracker velocityTracker = mVelocityTracker;
1685 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1686 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001687 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001688 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001689 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1690 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001691
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001692 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1693
Adam Cohen00481b32011-11-18 12:03:48 -08001694 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001695 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001696
Adam Cohenaefd4e12011-02-14 16:39:38 -08001697 // In the case that the page is moved far to one direction and then is flung
1698 // in the opposite direction, we use a threshold to determine whether we should
1699 // just return to the starting page, or if we should skip one further.
1700 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001701 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001702 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001703 returnToOriginalPage = true;
1704 }
1705
Adam Cohenaefd4e12011-02-14 16:39:38 -08001706 int finalPage;
1707 // We give flings precedence over large moves, which is why we short-circuit our
1708 // test for a large move if a fling has been registered. That is, a large
1709 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001710 final boolean isRtl = isLayoutRtl();
1711 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1712 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1713 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1714 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001715 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1716 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001717 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1718 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001719 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001720 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1721 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001722 } else {
1723 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001724 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001725 // at this point we have not moved beyond the touch slop
1726 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1727 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001728 int nextPage = Math.max(0, mCurrentPage - 1);
1729 if (nextPage != mCurrentPage) {
1730 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001731 } else {
1732 snapToDestination();
1733 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001734 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001735 // at this point we have not moved beyond the touch slop
1736 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1737 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001738 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1739 if (nextPage != mCurrentPage) {
1740 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001741 } else {
1742 snapToDestination();
1743 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001744 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1745 // Update the last motion position
1746 mLastMotionX = ev.getX();
1747 mLastMotionY = ev.getY();
1748
1749 // Update the parent down so that our zoom animations take this new movement into
1750 // account
1751 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1752 mParentDownMotionX = pt[0];
1753 mParentDownMotionY = pt[1];
1754 updateDragViewTranslationDuringDrag();
1755 boolean handledFling = false;
1756 if (!DISABLE_FLING_TO_DELETE) {
1757 // Check the velocity and see if we are flinging-to-delete
1758 PointF flingToDeleteVector = isFlingingToDelete();
1759 if (flingToDeleteVector != null) {
1760 onFlingToDelete(flingToDeleteVector);
1761 handledFling = true;
1762 }
1763 }
1764 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1765 (int) mParentDownMotionY)) {
1766 onDropToDelete();
1767 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001768 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001769 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001770 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001771
1772 // Remove the callback to wait for the side page hover timeout
1773 removeCallbacks(mSidePageHoverRunnable);
1774 // End any intermediate reordering states
1775 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001776 break;
1777
1778 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001779 if (mTouchState == TOUCH_STATE_SCROLLING) {
1780 snapToDestination();
1781 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001782 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001783 break;
1784
1785 case MotionEvent.ACTION_POINTER_UP:
1786 onSecondaryPointerUp(ev);
1787 break;
1788 }
1789
1790 return true;
1791 }
1792
Adam Cohen7d30a372013-07-01 17:03:59 -07001793 public void onFlingToDelete(View v) {}
1794 public void onRemoveView(View v, boolean deletePermanently) {}
1795 public void onRemoveViewAnimationCompleted() {}
1796 public void onAddView(View v, int index) {}
1797
1798 private void resetTouchState() {
1799 releaseVelocityTracker();
1800 endReordering();
1801 mTouchState = TOUCH_STATE_REST;
1802 mActivePointerId = INVALID_POINTER;
1803 mDownEventOnEdge = false;
1804 }
1805
1806 protected void onUnhandledTap(MotionEvent ev) {}
1807
Winson Chung185d7162011-02-28 13:47:29 -08001808 @Override
1809 public boolean onGenericMotionEvent(MotionEvent event) {
1810 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1811 switch (event.getAction()) {
1812 case MotionEvent.ACTION_SCROLL: {
1813 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1814 final float vscroll;
1815 final float hscroll;
1816 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1817 vscroll = 0;
1818 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1819 } else {
1820 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1821 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1822 }
1823 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001824 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1825 : (hscroll > 0 || vscroll > 0);
1826 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001827 scrollRight();
1828 } else {
1829 scrollLeft();
1830 }
1831 return true;
1832 }
1833 }
1834 }
1835 }
1836 return super.onGenericMotionEvent(event);
1837 }
1838
Michael Jurkab8f06722010-10-10 15:58:46 -07001839 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1840 if (mVelocityTracker == null) {
1841 mVelocityTracker = VelocityTracker.obtain();
1842 }
1843 mVelocityTracker.addMovement(ev);
1844 }
1845
1846 private void releaseVelocityTracker() {
1847 if (mVelocityTracker != null) {
1848 mVelocityTracker.recycle();
1849 mVelocityTracker = null;
1850 }
1851 }
1852
Winson Chung321e9ee2010-08-09 13:37:56 -07001853 private void onSecondaryPointerUp(MotionEvent ev) {
1854 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1855 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1856 final int pointerId = ev.getPointerId(pointerIndex);
1857 if (pointerId == mActivePointerId) {
1858 // This was our active pointer going up. Choose a new
1859 // active pointer and adjust accordingly.
1860 // TODO: Make this decision more intelligent.
1861 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1862 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1863 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001864 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001865 mActivePointerId = ev.getPointerId(newPointerIndex);
1866 if (mVelocityTracker != null) {
1867 mVelocityTracker.clear();
1868 }
1869 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001870 }
1871
Winson Chung321e9ee2010-08-09 13:37:56 -07001872 @Override
1873 public void requestChildFocus(View child, View focused) {
1874 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001875 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001876 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001877 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001878 }
1879 }
1880
Winson Chung1908d072011-02-24 18:09:44 -08001881 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001882 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001883 }
1884
Adam Cohen7d30a372013-07-01 17:03:59 -07001885 int getPageNearestToPoint(float x) {
1886 int index = 0;
1887 for (int i = 0; i < getChildCount(); ++i) {
1888 if (x < getChildAt(i).getRight() - getScrollX()) {
1889 return index;
1890 } else {
1891 index++;
1892 }
1893 }
1894 return Math.min(index, getChildCount() - 1);
1895 }
1896
Adam Cohend19d3ca2010-09-15 14:43:42 -07001897 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001898 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001899 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001900 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001901 final int childCount = getChildCount();
1902 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001903 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001904 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001905 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001906 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001907 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1908 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1909 minDistanceFromScreenCenter = distanceFromScreenCenter;
1910 minDistanceFromScreenCenterIndex = i;
1911 }
1912 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001913 return minDistanceFromScreenCenterIndex;
1914 }
1915
1916 protected void snapToDestination() {
1917 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001918 }
1919
Adam Cohene0f66b52010-11-23 15:06:07 -08001920 private static class ScrollInterpolator implements Interpolator {
1921 public ScrollInterpolator() {
1922 }
1923
1924 public float getInterpolation(float t) {
1925 t -= 1.0f;
1926 return t*t*t*t*t + 1;
1927 }
1928 }
1929
1930 // We want the duration of the page snap animation to be influenced by the distance that
1931 // the screen has to travel, however, we don't want this duration to be effected in a
1932 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1933 // of travel has on the overall snap duration.
1934 float distanceInfluenceForSnapDuration(float f) {
1935 f -= 0.5f; // center the values about 0.
1936 f *= 0.3f * Math.PI / 2.0f;
1937 return (float) Math.sin(f);
1938 }
1939
Michael Jurka0142d492010-08-25 17:46:15 -07001940 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001941 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001942 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001943
Winson Chung785d2eb2011-04-14 16:08:02 -07001944 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage));
1945 if (DEBUG) Log.d(TAG, "snapToPageWithVelocity.getRelativeChildOffset(): "
Adam Cohen7d30a372013-07-01 17:03:59 -07001946 + getViewportWidth() + ", " + getChildWidth(whichPage));
Adam Cohene0f66b52010-11-23 15:06:07 -08001947 final int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
1948 int delta = newX - mUnboundedScrollX;
1949 int duration = 0;
1950
Adam Cohen265b9a62011-12-07 14:37:18 -08001951 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001952 // If the velocity is low enough, then treat this more as an automatic page advance
1953 // as opposed to an apparent physical response to flinging
1954 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1955 return;
1956 }
1957
1958 // Here we compute a "distance" that will be used in the computation of the overall
1959 // snap duration. This is a function of the actual distance that needs to be traveled;
1960 // we keep this value close to half screen size in order to reduce the variance in snap
1961 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001962 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001963 float distance = halfScreenSize + halfScreenSize *
1964 distanceInfluenceForSnapDuration(distanceRatio);
1965
1966 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001967 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001968
1969 // we want the page's snap velocity to approximately match the velocity at which the
1970 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001971 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1972 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001973
1974 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001975 }
1976
1977 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001978 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001979 }
1980
Adam Cohen7d30a372013-07-01 17:03:59 -07001981 protected void snapToPageImmediately(int whichPage) {
1982 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1983 }
1984
Michael Jurka0142d492010-08-25 17:46:15 -07001985 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001986 snapToPage(whichPage, duration, false);
1987 }
1988
1989 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07001990 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07001991
Winson Chung785d2eb2011-04-14 16:08:02 -07001992 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage));
Adam Cohen7d30a372013-07-01 17:03:59 -07001993 if (DEBUG) Log.d(TAG, "snapToPage.getRelativeChildOffset(): " + getViewportWidth() + ", "
Winson Chung785d2eb2011-04-14 16:08:02 -07001994 + getChildWidth(whichPage));
Winson Chung86f77532010-08-24 11:08:22 -07001995 int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08001996 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001997 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07001998 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07001999 }
2000
2001 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002002 snapToPage(whichPage, delta, duration, false);
2003 }
Michael Jurka0142d492010-08-25 17:46:15 -07002004
Adam Cohen7d30a372013-07-01 17:03:59 -07002005 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2006 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002007 View focusedChild = getFocusedChild();
2008 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002009 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002010 focusedChild.clearFocus();
2011 }
2012
2013 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002014 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002015 if (immediate) {
2016 duration = 0;
2017 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002018 duration = Math.abs(delta);
2019 }
2020
2021 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002022 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002023
Michael Jurka0142d492010-08-25 17:46:15 -07002024 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002025
2026 // Trigger a compute() to finish switching pages if necessary
2027 if (immediate) {
2028 computeScroll();
2029 }
2030
2031 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002032 invalidate();
2033 }
2034
Winson Chung321e9ee2010-08-09 13:37:56 -07002035 public void scrollLeft() {
2036 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002037 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002038 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002039 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002040 }
2041 }
2042
2043 public void scrollRight() {
2044 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002045 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002046 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002047 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002048 }
2049 }
2050
Winson Chung86f77532010-08-24 11:08:22 -07002051 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002052 int result = -1;
2053 if (v != null) {
2054 ViewParent vp = v.getParent();
2055 int count = getChildCount();
2056 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002057 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002058 return i;
2059 }
2060 }
2061 }
2062 return result;
2063 }
2064
2065 /**
2066 * @return True is long presses are still allowed for the current touch
2067 */
2068 public boolean allowLongPress() {
2069 return mAllowLongPress;
2070 }
2071
Michael Jurka0142d492010-08-25 17:46:15 -07002072 /**
2073 * Set true to allow long-press events to be triggered, usually checked by
2074 * {@link Launcher} to accept or block dpad-initiated long-presses.
2075 */
2076 public void setAllowLongPress(boolean allowLongPress) {
2077 mAllowLongPress = allowLongPress;
2078 }
2079
Winson Chung321e9ee2010-08-09 13:37:56 -07002080 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002081 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002082
2083 SavedState(Parcelable superState) {
2084 super(superState);
2085 }
2086
2087 private SavedState(Parcel in) {
2088 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002089 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002090 }
2091
2092 @Override
2093 public void writeToParcel(Parcel out, int flags) {
2094 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002095 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002096 }
2097
2098 public static final Parcelable.Creator<SavedState> CREATOR =
2099 new Parcelable.Creator<SavedState>() {
2100 public SavedState createFromParcel(Parcel in) {
2101 return new SavedState(in);
2102 }
2103
2104 public SavedState[] newArray(int size) {
2105 return new SavedState[size];
2106 }
2107 };
2108 }
2109
Winson Chungf314b0e2011-08-16 11:54:27 -07002110 protected void loadAssociatedPages(int page) {
2111 loadAssociatedPages(page, false);
2112 }
2113 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002114 if (mContentIsRefreshable) {
2115 final int count = getChildCount();
2116 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002117 int lowerPageBound = getAssociatedLowerPageBound(page);
2118 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002119 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2120 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002121 // First, clear any pages that should no longer be loaded
2122 for (int i = 0; i < count; ++i) {
2123 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002124 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002125 if (layout.getPageChildCount() > 0) {
2126 layout.removeAllViewsOnPage();
2127 }
2128 mDirtyPageContent.set(i, true);
2129 }
2130 }
2131 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002132 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002133 if ((i != page) && immediateAndOnly) {
2134 continue;
2135 }
Michael Jurka0142d492010-08-25 17:46:15 -07002136 if (lowerPageBound <= i && i <= upperPageBound) {
2137 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002138 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002139 mDirtyPageContent.set(i, false);
2140 }
Winson Chung86f77532010-08-24 11:08:22 -07002141 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002142 }
2143 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002144 }
2145 }
2146
Winson Chunge3193b92010-09-10 11:44:42 -07002147 protected int getAssociatedLowerPageBound(int page) {
2148 return Math.max(0, page - 1);
2149 }
2150 protected int getAssociatedUpperPageBound(int page) {
2151 final int count = getChildCount();
2152 return Math.min(page + 1, count - 1);
2153 }
2154
Winson Chung86f77532010-08-24 11:08:22 -07002155 /**
2156 * This method is called ONLY to synchronize the number of pages that the paged view has.
2157 * To actually fill the pages with information, implement syncPageItems() below. It is
2158 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2159 * and therefore, individual page items do not need to be updated in this method.
2160 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002161 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002162
2163 /**
2164 * This method is called to synchronize the items that are on a particular page. If views on
2165 * the page can be reused, then they should be updated within this method.
2166 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002167 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002168
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002169 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002170 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002171 }
2172 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002173 invalidatePageData(currentPage, false);
2174 }
2175 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002176 if (!mIsDataReady) {
2177 return;
2178 }
2179
Michael Jurka0142d492010-08-25 17:46:15 -07002180 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002181 // Force all scrolling-related behavior to end
2182 mScroller.forceFinished(true);
2183 mNextPage = INVALID_PAGE;
2184
Michael Jurka0142d492010-08-25 17:46:15 -07002185 // Update all the pages
2186 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002187
Winson Chung5a808352011-06-27 19:08:49 -07002188 // We must force a measure after we've loaded the pages to update the content width and
2189 // to determine the full scroll width
2190 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2191 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2192
2193 // Set a new page as the current page if necessary
2194 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002195 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002196 }
2197
Michael Jurka0142d492010-08-25 17:46:15 -07002198 // Mark each of the pages as dirty
2199 final int count = getChildCount();
2200 mDirtyPageContent.clear();
2201 for (int i = 0; i < count; ++i) {
2202 mDirtyPageContent.add(true);
2203 }
2204
2205 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002206 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002207 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002208 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002209 }
Winson Chung007c6982011-06-14 13:27:53 -07002210
Adam Cohen7d30a372013-07-01 17:03:59 -07002211 // Animate the drag view back to the original position
2212 void animateDragViewToOriginalPosition() {
2213 if (mDragView != null) {
2214 AnimatorSet anim = new AnimatorSet();
2215 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2216 anim.playTogether(
2217 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2218 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2219 anim.addListener(new AnimatorListenerAdapter() {
2220 @Override
2221 public void onAnimationEnd(Animator animation) {
2222 onPostReorderingAnimationCompleted();
2223 }
2224 });
2225 anim.start();
2226 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002227 }
2228
Adam Cohen7d30a372013-07-01 17:03:59 -07002229 // "Zooms out" the PagedView to reveal more side pages
2230 protected boolean zoomOut() {
2231 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2232 mZoomInOutAnim.cancel();
2233 }
2234
2235 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2236 mZoomInOutAnim = new AnimatorSet();
2237 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2238 mZoomInOutAnim.playTogether(
2239 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2240 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2241 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2242 @Override
2243 public void onAnimationStart(Animator animation) {
2244 // Show the delete drop target
2245 if (mDeleteDropTarget != null) {
2246 mDeleteDropTarget.setVisibility(View.VISIBLE);
2247 mDeleteDropTarget.animate().alpha(1f)
2248 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2249 .setListener(new AnimatorListenerAdapter() {
2250 @Override
2251 public void onAnimationStart(Animator animation) {
2252 mDeleteDropTarget.setAlpha(0f);
2253 }
2254 });
2255 }
2256 }
2257 });
2258 mZoomInOutAnim.start();
2259 return true;
2260 }
2261 return false;
2262 }
2263
2264 protected void onStartReordering() {
2265 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2266 mTouchState = TOUCH_STATE_REORDERING;
2267 mIsReordering = true;
2268
2269 // Mark all the non-widget pages as invisible
2270 getVisiblePages(mTempVisiblePagesRange);
2271 boundByReorderablePages(true, mTempVisiblePagesRange);
2272 for (int i = 0; i < getPageCount(); ++i) {
2273 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2274 getPageAt(i).setAlpha(0f);
2275 }
2276 }
2277
2278 // We must invalidate to trigger a redraw to update the layers such that the drag view
2279 // is always drawn on top
2280 invalidate();
2281 }
2282
2283 private void onPostReorderingAnimationCompleted() {
2284 // Trigger the callback when reordering has settled
2285 --mPostReorderingPreZoomInRemainingAnimationCount;
2286 if (mPostReorderingPreZoomInRunnable != null &&
2287 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2288 mPostReorderingPreZoomInRunnable.run();
2289 mPostReorderingPreZoomInRunnable = null;
2290 }
2291 }
2292
2293 protected void onEndReordering() {
2294 mIsReordering = false;
2295
2296 // Mark all the non-widget pages as visible again
2297 getVisiblePages(mTempVisiblePagesRange);
2298 boundByReorderablePages(true, mTempVisiblePagesRange);
2299 for (int i = 0; i < getPageCount(); ++i) {
2300 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2301 getPageAt(i).setAlpha(1f);
2302 }
2303 }
2304 }
2305
2306 public boolean startReordering() {
2307 int dragViewIndex = getPageNearestToCenterOfScreen();
2308 mTempVisiblePagesRange[0] = 0;
2309 mTempVisiblePagesRange[1] = getPageCount() - 1;
2310 boundByReorderablePages(true, mTempVisiblePagesRange);
2311 mReorderingStarted = true;
2312
2313 // Check if we are within the reordering range
2314 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2315 dragViewIndex <= mTempVisiblePagesRange[1]) {
2316 if (zoomOut()) {
2317 // Find the drag view under the pointer
2318 mDragView = getChildAt(dragViewIndex);
2319
2320 onStartReordering();
2321 }
2322 return true;
2323 }
2324 return false;
2325 }
2326
2327 boolean isReordering(boolean testTouchState) {
2328 boolean state = mIsReordering;
2329 if (testTouchState) {
2330 state &= (mTouchState == TOUCH_STATE_REORDERING);
2331 }
2332 return state;
2333 }
2334 void endReordering() {
2335 // For simplicity, we call endReordering sometimes even if reordering was never started.
2336 // In that case, we don't want to do anything.
2337 if (!mReorderingStarted) return;
2338 mReorderingStarted = false;
2339
2340 // If we haven't flung-to-delete the current child, then we just animate the drag view
2341 // back into position
2342 final Runnable onCompleteRunnable = new Runnable() {
2343 @Override
2344 public void run() {
2345 onEndReordering();
2346 }
2347 };
2348 if (!mDeferringForDelete) {
2349 mPostReorderingPreZoomInRunnable = new Runnable() {
2350 public void run() {
2351 zoomIn(onCompleteRunnable);
2352 };
2353 };
2354
2355 mPostReorderingPreZoomInRemainingAnimationCount =
2356 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2357 // Snap to the current page
2358 snapToPage(indexOfChild(mDragView), 0);
2359 // Animate the drag view back to the front position
2360 animateDragViewToOriginalPosition();
2361 } else {
2362 // Handled in post-delete-animation-callbacks
2363 }
2364 }
2365
2366 // "Zooms in" the PagedView to highlight the current page
2367 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2368 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2369 mZoomInOutAnim.cancel();
2370 }
2371 if (getScaleX() < 1f || getScaleY() < 1f) {
2372 mZoomInOutAnim = new AnimatorSet();
2373 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2374 mZoomInOutAnim.playTogether(
2375 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2376 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2377 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2378 @Override
2379 public void onAnimationStart(Animator animation) {
2380 // Hide the delete drop target
2381 if (mDeleteDropTarget != null) {
2382 mDeleteDropTarget.animate().alpha(0f)
2383 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2384 .setListener(new AnimatorListenerAdapter() {
2385 @Override
2386 public void onAnimationEnd(Animator animation) {
2387 mDeleteDropTarget.setVisibility(View.GONE);
2388 }
2389 });
2390 }
2391 }
2392 @Override
2393 public void onAnimationCancel(Animator animation) {
2394 mDragView = null;
2395 }
2396 @Override
2397 public void onAnimationEnd(Animator animation) {
2398 mDragView = null;
2399 if (onCompleteRunnable != null) {
2400 onCompleteRunnable.run();
2401 }
2402 }
2403 });
2404 mZoomInOutAnim.start();
2405 return true;
2406 } else {
2407 if (onCompleteRunnable != null) {
2408 onCompleteRunnable.run();
2409 }
2410 }
2411 return false;
2412 }
2413
2414 /*
2415 * Flinging to delete - IN PROGRESS
2416 */
2417 private PointF isFlingingToDelete() {
2418 ViewConfiguration config = ViewConfiguration.get(getContext());
2419 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2420
2421 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2422 // Do a quick dot product test to ensure that we are flinging upwards
2423 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2424 mVelocityTracker.getYVelocity());
2425 PointF upVec = new PointF(0f, -1f);
2426 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2427 (vel.length() * upVec.length()));
2428 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2429 return vel;
2430 }
2431 }
2432 return null;
2433 }
2434
2435 /**
2436 * Creates an animation from the current drag view along its current velocity vector.
2437 * For this animation, the alpha runs for a fixed duration and we update the position
2438 * progressively.
2439 */
2440 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2441 private View mDragView;
2442 private PointF mVelocity;
2443 private Rect mFrom;
2444 private long mPrevTime;
2445 private float mFriction;
2446
2447 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2448
2449 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2450 long startTime, float friction) {
2451 mDragView = dragView;
2452 mVelocity = vel;
2453 mFrom = from;
2454 mPrevTime = startTime;
2455 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2456 }
2457
2458 @Override
2459 public void onAnimationUpdate(ValueAnimator animation) {
2460 float t = ((Float) animation.getAnimatedValue()).floatValue();
2461 long curTime = AnimationUtils.currentAnimationTimeMillis();
2462
2463 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2464 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2465
2466 mDragView.setTranslationX(mFrom.left);
2467 mDragView.setTranslationY(mFrom.top);
2468 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2469
2470 mVelocity.x *= mFriction;
2471 mVelocity.y *= mFriction;
2472 mPrevTime = curTime;
2473 }
2474 };
2475
2476 private static final int ANIM_TAG_KEY = 100;
2477
2478 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2479 return new Runnable() {
2480 @Override
2481 public void run() {
2482 int dragViewIndex = indexOfChild(dragView);
2483
2484 // For each of the pages around the drag view, animate them from the previous
2485 // position to the new position in the layout (as a result of the drag view moving
2486 // in the layout)
2487 // NOTE: We can make an assumption here because we have side-bound pages that we
2488 // will always have pages to animate in from the left
2489 getVisiblePages(mTempVisiblePagesRange);
2490 boundByReorderablePages(true, mTempVisiblePagesRange);
2491 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2492 boolean slideFromLeft = (isLastWidgetPage ||
2493 dragViewIndex > mTempVisiblePagesRange[0]);
2494
2495 // Setup the scroll to the correct page before we swap the views
2496 if (slideFromLeft) {
2497 snapToPageImmediately(dragViewIndex - 1);
2498 }
2499
2500 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2501 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2502 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2503 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2504 ArrayList<Animator> animations = new ArrayList<Animator>();
2505 for (int i = lowerIndex; i <= upperIndex; ++i) {
2506 View v = getChildAt(i);
2507 // dragViewIndex < pageUnderPointIndex, so after we remove the
2508 // drag view all subsequent views to pageUnderPointIndex will
2509 // shift down.
2510 int oldX = 0;
2511 int newX = 0;
2512 if (slideFromLeft) {
2513 if (i == 0) {
2514 // Simulate the page being offscreen with the page spacing
2515 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2516 - mPageSpacing;
2517 } else {
2518 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2519 }
2520 newX = getViewportOffsetX() + getChildOffset(i);
2521 } else {
2522 oldX = getChildOffset(i) - getChildOffset(i - 1);
2523 newX = 0;
2524 }
2525
2526 // Animate the view translation from its old position to its new
2527 // position
2528 AnimatorSet anim = (AnimatorSet) v.getTag();
2529 if (anim != null) {
2530 anim.cancel();
2531 }
2532
2533 // Note: Hacky, but we want to skip any optimizations to not draw completely
2534 // hidden views
2535 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2536 v.setTranslationX(oldX - newX);
2537 anim = new AnimatorSet();
2538 anim.playTogether(
2539 ObjectAnimator.ofFloat(v, "translationX", 0f),
2540 ObjectAnimator.ofFloat(v, "alpha", 1f));
2541 animations.add(anim);
2542 v.setTag(ANIM_TAG_KEY, anim);
2543 }
2544
2545 AnimatorSet slideAnimations = new AnimatorSet();
2546 slideAnimations.playTogether(animations);
2547 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2548 slideAnimations.addListener(new AnimatorListenerAdapter() {
2549 @Override
2550 public void onAnimationEnd(Animator animation) {
2551 final Runnable onCompleteRunnable = new Runnable() {
2552 @Override
2553 public void run() {
2554 mDeferringForDelete = false;
2555 onEndReordering();
2556 onRemoveViewAnimationCompleted();
2557 }
2558 };
2559 zoomIn(onCompleteRunnable);
2560 }
2561 });
2562 slideAnimations.start();
2563
2564 removeView(dragView);
2565 onRemoveView(dragView, true);
2566 }
2567 };
2568 }
2569
2570 public void onFlingToDelete(PointF vel) {
2571 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2572
2573 // NOTE: Because it takes time for the first frame of animation to actually be
2574 // called and we expect the animation to be a continuation of the fling, we have
2575 // to account for the time that has elapsed since the fling finished. And since
2576 // we don't have a startDelay, we will always get call to update when we call
2577 // start() (which we want to ignore).
2578 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2579 private int mCount = -1;
2580 private long mStartTime;
2581 private float mOffset;
2582 /* Anonymous inner class ctor */ {
2583 mStartTime = startTime;
2584 }
2585
2586 @Override
2587 public float getInterpolation(float t) {
2588 if (mCount < 0) {
2589 mCount++;
2590 } else if (mCount == 0) {
2591 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2592 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2593 mCount++;
2594 }
2595 return Math.min(1f, mOffset + t);
2596 }
2597 };
2598
2599 final Rect from = new Rect();
2600 final View dragView = mDragView;
2601 from.left = (int) dragView.getTranslationX();
2602 from.top = (int) dragView.getTranslationY();
2603 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2604 from, startTime, FLING_TO_DELETE_FRICTION);
2605
2606 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2607
2608 // Create and start the animation
2609 ValueAnimator mDropAnim = new ValueAnimator();
2610 mDropAnim.setInterpolator(tInterpolator);
2611 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2612 mDropAnim.setFloatValues(0f, 1f);
2613 mDropAnim.addUpdateListener(updateCb);
2614 mDropAnim.addListener(new AnimatorListenerAdapter() {
2615 public void onAnimationEnd(Animator animation) {
2616 onAnimationEndRunnable.run();
2617 }
2618 });
2619 mDropAnim.start();
2620 mDeferringForDelete = true;
2621 }
2622
2623 /* Drag to delete */
2624 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2625 if (mDeleteDropTarget != null) {
2626 mAltTmpRect.set(0, 0, 0, 0);
2627 View parent = (View) mDeleteDropTarget.getParent();
2628 if (parent != null) {
2629 parent.getGlobalVisibleRect(mAltTmpRect);
2630 }
2631 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2632 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2633 return mTmpRect.contains(x, y);
2634 }
2635 return false;
2636 }
2637
2638 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2639
2640 private void onDropToDelete() {
2641 final View dragView = mDragView;
2642
2643 final float toScale = 0f;
2644 final float toAlpha = 0f;
2645
2646 // Create and start the complex animation
2647 ArrayList<Animator> animations = new ArrayList<Animator>();
2648 AnimatorSet motionAnim = new AnimatorSet();
2649 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2650 motionAnim.playTogether(
2651 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2652 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2653 animations.add(motionAnim);
2654
2655 AnimatorSet alphaAnim = new AnimatorSet();
2656 alphaAnim.setInterpolator(new LinearInterpolator());
2657 alphaAnim.playTogether(
2658 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2659 animations.add(alphaAnim);
2660
2661 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2662
2663 AnimatorSet anim = new AnimatorSet();
2664 anim.playTogether(animations);
2665 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2666 anim.addListener(new AnimatorListenerAdapter() {
2667 public void onAnimationEnd(Animator animation) {
2668 onAnimationEndRunnable.run();
2669 }
2670 });
2671 anim.start();
2672
2673 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002674 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002675
2676 /* Accessibility */
2677 @Override
2678 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2679 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002680 info.setScrollable(getPageCount() > 1);
2681 if (getCurrentPage() < getPageCount() - 1) {
2682 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2683 }
2684 if (getCurrentPage() > 0) {
2685 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2686 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002687 }
2688
2689 @Override
2690 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2691 super.onInitializeAccessibilityEvent(event);
2692 event.setScrollable(true);
2693 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2694 event.setFromIndex(mCurrentPage);
2695 event.setToIndex(mCurrentPage);
2696 event.setItemCount(getChildCount());
2697 }
2698 }
2699
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002700 @Override
2701 public boolean performAccessibilityAction(int action, Bundle arguments) {
2702 if (super.performAccessibilityAction(action, arguments)) {
2703 return true;
2704 }
2705 switch (action) {
2706 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2707 if (getCurrentPage() < getPageCount() - 1) {
2708 scrollRight();
2709 return true;
2710 }
2711 } break;
2712 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2713 if (getCurrentPage() > 0) {
2714 scrollLeft();
2715 return true;
2716 }
2717 } break;
2718 }
2719 return false;
2720 }
2721
Adam Cohen0ffac432013-07-10 11:19:26 -07002722 protected String getCurrentPageDescription() {
2723 return String.format(getContext().getString(R.string.default_scroll_format),
2724 getNextPage() + 1, getChildCount());
2725 }
2726
Winson Chungd11265e2011-08-30 13:37:23 -07002727 @Override
2728 public boolean onHoverEvent(android.view.MotionEvent event) {
2729 return true;
2730 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002731}