blob: cb75f2a70f9ebefc2e555ddeaf5f038d115a293b [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 Cohenedb40762013-07-18 16:45:45 -0700124
125 private int[] mPageScrolls;
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];
Winson Chungc9ca2982013-07-19 12:07:38 -0700232 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700233 private Rect mTmpRect = new Rect();
234 private Rect mAltTmpRect = new Rect();
235
236 // Fling to delete
237 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
238 private float FLING_TO_DELETE_FRICTION = 0.035f;
239 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
240 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
241 protected int mFlingToDeleteThresholdVelocity = -1400;
242 // Drag to delete
243 private boolean mDeferringForDelete = false;
244 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
245 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
246
247 // Drop to delete
248 private View mDeleteDropTarget;
249
250 private boolean mAutoComputePageSpacing = false;
251 private boolean mRecomputePageSpacing = false;
252
253 // Bouncer
254 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700255
Winson Chung86f77532010-08-24 11:08:22 -0700256 public interface PageSwitchListener {
257 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700258 }
259
Winson Chung321e9ee2010-08-09 13:37:56 -0700260 public PagedView(Context context) {
261 this(context, null);
262 }
263
264 public PagedView(Context context, AttributeSet attrs) {
265 this(context, attrs, 0);
266 }
267
268 public PagedView(Context context, AttributeSet attrs, int defStyle) {
269 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700270
Adam Cohen9c4949e2010-10-05 12:27:22 -0700271 TypedArray a = context.obtainStyledAttributes(attrs,
272 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800273 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700274 if (mPageSpacing < 0) {
275 mAutoComputePageSpacing = mRecomputePageSpacing = true;
276 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700277 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800278 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700279 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800280 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700281 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800282 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700283 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800284 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700285 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700286 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700287 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700288 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700289 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700290 a.recycle();
291
Winson Chung321e9ee2010-08-09 13:37:56 -0700292 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700293 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700294 }
295
296 /**
297 * Initializes various states for this workspace.
298 */
Michael Jurka0142d492010-08-25 17:46:15 -0700299 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700300 mDirtyPageContent = new ArrayList<Boolean>();
301 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800302 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700303 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700304 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700305
306 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700307 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700308 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
309 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700310 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800311
Adam Cohen7d30a372013-07-01 17:03:59 -0700312 // Scale the fling-to-delete threshold by the density
313 mFlingToDeleteThresholdVelocity =
314 (int) (mFlingToDeleteThresholdVelocity * mDensity);
315
Adam Cohen265b9a62011-12-07 14:37:18 -0800316 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
317 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
318 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700319 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700320 }
321
Winson Chungd2be3812013-07-16 11:11:32 -0700322 protected void onAttachedToWindow() {
323 // Hook up the page indicator
324 ViewGroup parent = (ViewGroup) getParent();
325 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
326 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
327 mPageIndicator.removeAllMarkers();
328 mPageIndicator.addMarkers(getChildCount());
329 }
330 }
331
332 protected void onDetachedFromWindow() {
333 // Unhook the page indicator
334 mPageIndicator = null;
335 }
336
Adam Cohen7d30a372013-07-01 17:03:59 -0700337 void setDeleteDropTarget(View v) {
338 mDeleteDropTarget = v;
339 }
340
341 // Convenience methods to map points from self to parent and vice versa
342 float[] mapPointFromViewToParent(View v, float x, float y) {
343 mTmpPoint[0] = x;
344 mTmpPoint[1] = y;
345 v.getMatrix().mapPoints(mTmpPoint);
346 mTmpPoint[0] += v.getLeft();
347 mTmpPoint[1] += v.getTop();
348 return mTmpPoint;
349 }
350 float[] mapPointFromParentToView(View v, float x, float y) {
351 mTmpPoint[0] = x - v.getLeft();
352 mTmpPoint[1] = y - v.getTop();
353 v.getMatrix().invert(mTmpInvMatrix);
354 mTmpInvMatrix.mapPoints(mTmpPoint);
355 return mTmpPoint;
356 }
357
358 void updateDragViewTranslationDuringDrag() {
359 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
360 float y = mLastMotionY - mDownMotionY;
361 mDragView.setTranslationX(x);
362 mDragView.setTranslationY(y);
363
364 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
365 }
366
367 public void setMinScale(float f) {
368 mMinScale = f;
369 requestLayout();
370 }
371
372 @Override
373 public void setScaleX(float scaleX) {
374 super.setScaleX(scaleX);
375 if (isReordering(true)) {
376 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
377 mLastMotionX = p[0];
378 mLastMotionY = p[1];
379 updateDragViewTranslationDuringDrag();
380 }
381 }
382
383 // Convenience methods to get the actual width/height of the PagedView (since it is measured
384 // to be larger to account for the minimum possible scale)
385 int getViewportWidth() {
386 return mViewport.width();
387 }
388 int getViewportHeight() {
389 return mViewport.height();
390 }
391
392 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
393 // PagedView both horizontally and vertically
394 int getViewportOffsetX() {
395 return (getMeasuredWidth() - getViewportWidth()) / 2;
396 }
397
398 int getViewportOffsetY() {
399 return (getMeasuredHeight() - getViewportHeight()) / 2;
400 }
401
Adam Cohenedb40762013-07-18 16:45:45 -0700402 PageIndicator getPageIndicator() {
403 return mPageIndicator;
404 }
405
Winson Chung86f77532010-08-24 11:08:22 -0700406 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
407 mPageSwitchListener = pageSwitchListener;
408 if (mPageSwitchListener != null) {
409 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700410 }
411 }
412
413 /**
Winson Chung52aee602013-01-30 12:01:02 -0800414 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
415 */
416 public boolean isLayoutRtl() {
417 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
418 }
419
420 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700421 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
422 * out pages.
423 */
424 protected void setDataIsReady() {
425 mIsDataReady = true;
426 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700427
Winson Chungf0ea4d32011-06-06 14:27:16 -0700428 protected boolean isDataReady() {
429 return mIsDataReady;
430 }
431
432 /**
Winson Chung86f77532010-08-24 11:08:22 -0700433 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700434 *
Winson Chung86f77532010-08-24 11:08:22 -0700435 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700436 */
Winson Chung86f77532010-08-24 11:08:22 -0700437 int getCurrentPage() {
438 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700439 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700440
Winson Chung360e63f2012-04-27 13:48:05 -0700441 int getNextPage() {
442 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
443 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700444
Winson Chung86f77532010-08-24 11:08:22 -0700445 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700446 return getChildCount();
447 }
448
Winson Chung86f77532010-08-24 11:08:22 -0700449 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700450 return getChildAt(index);
451 }
452
Adam Cohenae4f1552011-10-20 00:15:42 -0700453 protected int indexToPage(int index) {
454 return index;
455 }
456
Winson Chung321e9ee2010-08-09 13:37:56 -0700457 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800458 * Updates the scroll of the current page immediately to its final scroll position. We use this
459 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
460 * the previous tab page.
461 */
462 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700463 // If the current page is invalid, just reset the scroll position to zero
464 int newX = 0;
465 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700466 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700467 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800468 scrollTo(newX, 0);
469 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800470 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800471 }
472
473 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700474 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
475 * ends, {@link #resumeScrolling()} should be called, along with
476 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
477 */
478 void pauseScrolling() {
479 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700480 }
481
482 /**
483 * Enables scrolling again.
484 * @see #pauseScrolling()
485 */
486 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700487 }
488 /**
Winson Chung86f77532010-08-24 11:08:22 -0700489 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700490 */
Winson Chung86f77532010-08-24 11:08:22 -0700491 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800492 if (!mScroller.isFinished()) {
493 mScroller.abortAnimation();
494 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800495 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
496 // the default
497 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800498 return;
499 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700500
Adam Cohene61a9a22013-06-11 15:45:31 -0700501 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700502 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700503 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700504 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800505 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700506 }
507
Michael Jurka0142d492010-08-25 17:46:15 -0700508 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700509 if (mPageSwitchListener != null) {
510 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700511 }
Winson Chungd2be3812013-07-16 11:11:32 -0700512
513 // Update the page indicator (when we aren't reordering)
514 if (mPageIndicator != null && !isReordering(false)) {
515 mPageIndicator.setActiveMarker(getNextPage());
516 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700517 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800518 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700519 if (!mIsPageMoving) {
520 mIsPageMoving = true;
521 onPageBeginMoving();
522 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700523 }
524
Michael Jurkace7e05f2011-02-01 22:02:35 -0800525 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700526 if (mIsPageMoving) {
527 mIsPageMoving = false;
528 onPageEndMoving();
529 }
Michael Jurka0142d492010-08-25 17:46:15 -0700530 }
531
Adam Cohen26976d92011-03-22 15:33:33 -0700532 protected boolean isPageMoving() {
533 return mIsPageMoving;
534 }
535
Michael Jurka0142d492010-08-25 17:46:15 -0700536 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700537 protected void onPageBeginMoving() {
538 }
539
540 // a method that subclasses can override to add behavior
541 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700542 }
543
Winson Chung321e9ee2010-08-09 13:37:56 -0700544 /**
Winson Chung86f77532010-08-24 11:08:22 -0700545 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700546 *
547 * @param l The listener used to respond to long clicks.
548 */
549 @Override
550 public void setOnLongClickListener(OnLongClickListener l) {
551 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700552 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700553 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700554 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700555 }
556 }
557
558 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800559 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700560 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800561 }
562
563 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700564 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700565 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800566 mUnboundedScrollX = x;
567
Adam Cohen0ffac432013-07-10 11:19:26 -0700568 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
569 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
570 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800571 super.scrollTo(0, y);
572 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700573 if (isRtl) {
574 overScroll(x - mMaxScrollX);
575 } else {
576 overScroll(x);
577 }
Adam Cohen68d73932010-11-15 10:50:58 -0800578 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700579 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800580 super.scrollTo(mMaxScrollX, y);
581 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700582 if (isRtl) {
583 overScroll(x);
584 } else {
585 overScroll(x - mMaxScrollX);
586 }
Adam Cohen68d73932010-11-15 10:50:58 -0800587 }
588 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800589 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800590 super.scrollTo(x, y);
591 }
592
Michael Jurka0142d492010-08-25 17:46:15 -0700593 mTouchX = x;
594 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700595
596 // Update the last motion events when scrolling
597 if (isReordering(true)) {
598 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
599 mLastMotionX = p[0];
600 mLastMotionY = p[1];
601 updateDragViewTranslationDuringDrag();
602 }
Michael Jurka0142d492010-08-25 17:46:15 -0700603 }
604
605 // we moved this functionality to a helper function so SmoothPagedView can reuse it
606 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700607 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700608 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700609 if (getScrollX() != mScroller.getCurrX()
610 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700611 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700612 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
613 }
Michael Jurka0142d492010-08-25 17:46:15 -0700614 invalidate();
615 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700616 } else if (mNextPage != INVALID_PAGE) {
617 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700618 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700619 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700620
Adam Cohen73aa9752010-11-24 16:26:58 -0800621 // We don't want to trigger a page end moving unless the page has settled
622 // and the user has stopped scrolling
623 if (mTouchState == TOUCH_STATE_REST) {
624 pageEndMoving();
625 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700626
Adam Cohen7d30a372013-07-01 17:03:59 -0700627 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700628 // Notify the user when the page changes
629 AccessibilityManager accessibilityManager = (AccessibilityManager)
630 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
631 if (accessibilityManager.isEnabled()) {
632 AccessibilityEvent ev =
633 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
634 ev.getText().add(getCurrentPageDescription());
635 sendAccessibilityEventUnchecked(ev);
636 }
Michael Jurka0142d492010-08-25 17:46:15 -0700637 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700638 }
Michael Jurka0142d492010-08-25 17:46:15 -0700639 return false;
640 }
641
642 @Override
643 public void computeScroll() {
644 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700645 }
646
Adam Cohen7d30a372013-07-01 17:03:59 -0700647 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
648 return mTopAlignPageWhenShrinkingForBouncer;
649 }
650
Adam Cohen96d30a12013-07-16 18:13:21 -0700651 public static class LayoutParams extends ViewGroup.LayoutParams {
652 public boolean isFullScreenPage = false;
653
654 /**
655 * {@inheritDoc}
656 */
657 public LayoutParams(int width, int height) {
658 super(width, height);
659 }
660
661 public LayoutParams(ViewGroup.LayoutParams source) {
662 super(source);
663 }
664 }
665
666 protected LayoutParams generateDefaultLayoutParams() {
667 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
668 }
669
Adam Cohenedb40762013-07-18 16:45:45 -0700670 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700671 LayoutParams lp = generateDefaultLayoutParams();
672 lp.isFullScreenPage = true;
673 super.addView(page, 0, lp);
674 }
675
Winson Chung321e9ee2010-08-09 13:37:56 -0700676 @Override
677 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700678 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700679 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
680 return;
681 }
682
Adam Cohen7d30a372013-07-01 17:03:59 -0700683 // We measure the dimensions of the PagedView to be larger than the pages so that when we
684 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700685 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
686 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
687 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700688 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700689 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
690 // viewport, we can be at most one and a half screens offset once we scale down
691 DisplayMetrics dm = getResources().getDisplayMetrics();
692 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
693 int parentWidthSize = (int) (1.5f * maxSize);
694 int parentHeightSize = maxSize;
695 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
696 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
697 mViewport.set(0, 0, widthSize, heightSize);
698
699 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
700 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
701 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700702 }
703
Winson Chung8aad6102012-05-11 16:27:49 -0700704 // Return early if we aren't given a proper dimension
705 if (widthSize <= 0 || heightSize <= 0) {
706 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
707 return;
708 }
709
Adam Lesinski6b879f02010-11-04 16:15:23 -0700710 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
711 * of the All apps view on XLarge displays to not take up more space then it needs. Width
712 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
713 * each page to have the same width.
714 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700715 final int verticalPadding = getPaddingTop() + getPaddingBottom();
716 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700717
718 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700719 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700720 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700721 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
722 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
723 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
724 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700725 final int childCount = getChildCount();
726 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700727 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700728 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700729 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
730
731 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700732 int childHeightMode;
733 int childWidth;
734 int childHeight;
735
736 if (!lp.isFullScreenPage) {
737 if (lp.width == LayoutParams.WRAP_CONTENT) {
738 childWidthMode = MeasureSpec.AT_MOST;
739 } else {
740 childWidthMode = MeasureSpec.EXACTLY;
741 }
742
743 if (lp.height == LayoutParams.WRAP_CONTENT) {
744 childHeightMode = MeasureSpec.AT_MOST;
745 } else {
746 childHeightMode = MeasureSpec.EXACTLY;
747 }
748
749 childWidth = widthSize - horizontalPadding;
750 childHeight = heightSize - verticalPadding;
751
Michael Jurka5f1c5092010-09-03 14:15:02 -0700752 } else {
753 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700754 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700755
756 childWidth = getViewportWidth();
757 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700758 }
759
760 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700761 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
762 final int childHeightMeasureSpec =
763 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700764 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700765 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700766 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700767
Winson Chunga128a7b2012-04-30 15:23:15 -0700768 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700769 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700770 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700771 // The gap between pages in the PagedView should be equal to the gap from the page
772 // to the edge of the screen (so it is not visible in the current screen). To
773 // account for unequal padding on each side of the paged view, we take the maximum
774 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700775 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700776 int spacing = Math.max(offset, widthSize - offset -
777 getChildAt(0).getMeasuredWidth());
778 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700779 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700780 }
781 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700782 }
783
Adam Cohen60b07122011-11-14 17:26:06 -0800784 public void setPageSpacing(int pageSpacing) {
785 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700786 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800787 }
788
Winson Chung321e9ee2010-08-09 13:37:56 -0700789 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700790 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700791 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700792 return;
793 }
794
Winson Chung785d2eb2011-04-14 16:08:02 -0700795 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700796 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700797
Adam Cohenedb40762013-07-18 16:45:45 -0700798 int screenWidth = getViewportWidth();
799
Adam Cohen7d30a372013-07-01 17:03:59 -0700800 int offsetX = getViewportOffsetX();
801 int offsetY = getViewportOffsetY();
802
803 // Update the viewport offsets
804 mViewport.offset(offsetX, offsetY);
805
Adam Cohen0ffac432013-07-10 11:19:26 -0700806 final boolean isRtl = isLayoutRtl();
807
808 final int startIndex = isRtl ? childCount - 1 : 0;
809 final int endIndex = isRtl ? -1 : childCount;
810 final int delta = isRtl ? -1 : 1;
811
Adam Cohen7d30a372013-07-01 17:03:59 -0700812 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700813 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
814
815 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
816 mPageScrolls = new int[getChildCount()];
817 }
818
Adam Cohen0ffac432013-07-10 11:19:26 -0700819 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700820 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700821 LayoutParams lp = (LayoutParams) child.getLayoutParams();
822 int childTop;
823
824 if (lp.isFullScreenPage) {
825 childTop = offsetY;
826 } else {
827 childTop = offsetY + getPaddingTop();
828 if (mCenterPagesVertically) {
829 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
830 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700831 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700832
Winson Chung321e9ee2010-08-09 13:37:56 -0700833 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700834 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700835 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800836
Winson Chung785d2eb2011-04-14 16:08:02 -0700837 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700838 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800839 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700840
841 // We assume the left and right padding are equal, and hence center the pages
842 // horizontally
843 int scrollOffset = false ? 0 : (getViewportWidth() - childWidth) / 2;
844 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
845
Adam Cohen9c4949e2010-10-05 12:27:22 -0700846 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700847 }
848 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700849
850 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
851 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800852 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700853 setHorizontalScrollBarEnabled(true);
854 mFirstLayout = false;
855 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700856
857 if (childCount > 0) {
858 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700859 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700860 } else {
861 mMaxScrollX = 0;
862 }
863
864 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
865 !mDeferringForDelete) {
866 setCurrentPage(getNextPage());
867 }
868 mChildCountOnLastLayout = getChildCount();
Winson Chunge3193b92010-09-10 11:44:42 -0700869 }
870
Adam Cohenf34bab52010-09-30 14:11:56 -0700871 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700872 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
873
874 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700875 for (int i = 0; i < getChildCount(); i++) {
876 View child = getChildAt(i);
877 if (child != null) {
878 float scrollProgress = getScrollProgress(screenCenter, child, i);
879 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800880 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700881 }
882 }
883 invalidate();
884 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700885 }
886
Winson Chunge3193b92010-09-10 11:44:42 -0700887 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700888 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700889 // Update the page indicator, we don't update the page indicator as we
890 // add/remove pages
891 if (mPageIndicator != null && !isReordering(false)) {
892 mPageIndicator.addMarker(indexOfChild(child));
893 }
894
Adam Cohen2591f6a2011-10-25 14:36:40 -0700895 // This ensures that when children are added, they get the correct transforms / alphas
896 // in accordance with any scroll effects.
897 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700898 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700899
Adam Cohen2591f6a2011-10-25 14:36:40 -0700900 invalidate();
901 }
902
Michael Jurka8b805b12012-04-18 14:23:14 -0700903 @Override
904 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700905 mForceScreenScrolled = true;
906 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700907 }
908
Winson Chungd2be3812013-07-16 11:11:32 -0700909 private void removeMarkerForView(int index) {
910 // Update the page indicator, we don't update the page indicator as we
911 // add/remove pages
912 if (mPageIndicator != null && !isReordering(false)) {
913 mPageIndicator.removeMarker(index);
914 }
915 }
916
917 @Override
918 public void removeView(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.removeView(v);
923 }
924 @Override
925 public void removeViewInLayout(View v) {
926 // XXX: We should find a better way to hook into this before the view
927 // gets removed form its parent...
928 removeMarkerForView(indexOfChild(v));
929 super.removeViewInLayout(v);
930 }
931 @Override
932 public void removeViewAt(int index) {
933 // XXX: We should find a better way to hook into this before the view
934 // gets removed form its parent...
935 removeViewAt(index);
936 super.removeViewAt(index);
937 }
938 @Override
939 public void removeAllViewsInLayout() {
940 // Update the page indicator, we don't update the page indicator as we
941 // add/remove pages
942 if (mPageIndicator != null) {
943 mPageIndicator.removeAllMarkers();
944 }
945
946 super.removeAllViewsInLayout();
947 }
948
Adam Cohen73894962011-10-31 13:17:17 -0700949 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700950 if (index < 0 || index > getChildCount() - 1) return 0;
951
Adam Cohen0ffac432013-07-10 11:19:26 -0700952 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700953
Adam Cohenf698c6e2013-07-17 18:44:25 -0700954 if (isRtl) index = getChildCount() - index - 1;
955 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -0700956
Adam Cohenf698c6e2013-07-17 18:44:25 -0700957 return offset;
Adam Cohen73894962011-10-31 13:17:17 -0700958 }
959
Winson Chungc9ca2982013-07-19 12:07:38 -0700960 void getReorderablePages(int[] range) {
961 range[0] = 0;
962 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -0700963 }
964
Michael Jurkadde558b2011-11-09 22:09:06 -0800965 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -0700966 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -0700967 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -0700968
Michael Jurkac4fb9172010-09-02 17:19:20 -0700969 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -0700970 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -0700971 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -0700972 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -0700973
Winson Chungc9ca2982013-07-19 12:07:38 -0700974 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
975 View currPage = getPageAt(leftScreen);
976
977 // Check if the right edge of the page is in the viewport
978 mTmpIntPoint[0] = currPage.getMeasuredWidth();
979 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
980 if (mTmpIntPoint[0] < 0) {
981 break;
982 }
983 }
984 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
985 View currPage = getPageAt(rightScreen);
986
987 // Check if the left edge of the page is in the viewport
988 mTmpIntPoint[0] = 0;
989 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
990 if (mTmpIntPoint[0] >= viewportWidth) {
991 break;
992 }
993 }
994 range[0] = Math.max(0, leftScreen);
995 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -0800996 } else {
997 range[0] = -1;
998 range[1] = -1;
999 }
1000 }
1001
Michael Jurka920d7f42012-05-14 16:29:55 -07001002 protected boolean shouldDrawChild(View child) {
1003 return child.getAlpha() > 0;
1004 }
1005
Michael Jurkadde558b2011-11-09 22:09:06 -08001006 @Override
1007 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001008 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001009 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1010 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001011 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001012
1013 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001014 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1015 // set it for the next frame
1016 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001017 screenScrolled(screenCenter);
1018 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001019 }
1020
1021 // Find out which screens are visible; as an optimization we only call draw on them
1022 final int pageCount = getChildCount();
1023 if (pageCount > 0) {
1024 getVisiblePages(mTempVisiblePagesRange);
1025 final int leftScreen = mTempVisiblePagesRange[0];
1026 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001027 if (leftScreen != -1 && rightScreen != -1) {
1028 final long drawingTime = getDrawingTime();
1029 // Clip to the bounds
1030 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001031 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1032 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001033
Adam Cohen7d30a372013-07-01 17:03:59 -07001034 // Draw all the children, leaving the drag view for last
1035 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001036 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001037 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001038 if (mForceDrawAllChildrenNextFrame ||
1039 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001040 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001041 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001042 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001043 // Draw the drag view on top (if there is one)
1044 if (mDragView != null) {
1045 drawChild(canvas, mDragView, drawingTime);
1046 }
1047
Michael Jurka5e368ff2012-05-14 23:13:15 -07001048 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001049 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001050 }
Michael Jurka0142d492010-08-25 17:46:15 -07001051 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001052 }
1053
1054 @Override
1055 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001056 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001057 if (page != mCurrentPage || !mScroller.isFinished()) {
1058 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001059 return true;
1060 }
1061 return false;
1062 }
1063
1064 @Override
1065 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001066 int focusablePage;
1067 if (mNextPage != INVALID_PAGE) {
1068 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001069 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001070 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001071 }
Winson Chung86f77532010-08-24 11:08:22 -07001072 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001073 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001074 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001075 }
1076 return false;
1077 }
1078
1079 @Override
1080 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001081 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001082 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001083 if (getCurrentPage() > 0) {
1084 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001085 return true;
1086 }
1087 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001088 if (getCurrentPage() < getPageCount() - 1) {
1089 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001090 return true;
1091 }
1092 }
1093 return super.dispatchUnhandledMove(focused, direction);
1094 }
1095
1096 @Override
1097 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001098 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001099 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001100 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001101 }
1102 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001103 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001104 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001105 }
1106 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001107 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001108 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001109 }
1110 }
1111 }
1112
1113 /**
1114 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001115 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001116 *
Winson Chung86f77532010-08-24 11:08:22 -07001117 * This happens when live folders requery, and if they're off page, they
1118 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001119 */
1120 @Override
1121 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001122 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001123 View v = focused;
1124 while (true) {
1125 if (v == current) {
1126 super.focusableViewAvailable(focused);
1127 return;
1128 }
1129 if (v == this) {
1130 return;
1131 }
1132 ViewParent parent = v.getParent();
1133 if (parent instanceof View) {
1134 v = (View)v.getParent();
1135 } else {
1136 return;
1137 }
1138 }
1139 }
1140
1141 /**
1142 * {@inheritDoc}
1143 */
1144 @Override
1145 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1146 if (disallowIntercept) {
1147 // We need to make sure to cancel our long press if
1148 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001149 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001150 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001151 }
1152 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1153 }
1154
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001155 /**
1156 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1157 */
1158 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001159 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001160 if (isLayoutRtl()) {
1161 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001162 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001163 }
Adam Cohenedb40762013-07-18 16:45:45 -07001164 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001165 }
1166
1167 /**
1168 * Return true if a tap at (x, y) should trigger a flip to the next page.
1169 */
1170 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001171 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001172 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001173 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001174 }
1175 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001176 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001177 }
Winson Chung52aee602013-01-30 12:01:02 -08001178
Adam Cohen7d30a372013-07-01 17:03:59 -07001179 /** Returns whether x and y originated within the buffered viewport */
1180 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1181 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1182 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1183 return mTmpRect.contains(x, y);
1184 }
1185
1186 /** Returns whether x and y originated within the current page view bounds */
1187 private boolean isTouchPointInCurrentPage(int x, int y) {
1188 View v = getPageAt(getCurrentPage());
1189 if (v != null) {
1190 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1191 v.getBottom());
1192 return mTmpRect.contains(x, y);
1193 }
1194 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001195 }
1196
Winson Chung321e9ee2010-08-09 13:37:56 -07001197 @Override
1198 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001199 if (DISABLE_TOUCH_INTERACTION) {
1200 return false;
1201 }
1202
Winson Chung321e9ee2010-08-09 13:37:56 -07001203 /*
1204 * This method JUST determines whether we want to intercept the motion.
1205 * If we return true, onTouchEvent will be called and we do the actual
1206 * scrolling there.
1207 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001208 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001209
Winson Chung45e1d6e2010-11-09 17:19:49 -08001210 // Skip touch handling if there are no pages to swipe
1211 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1212
Winson Chung321e9ee2010-08-09 13:37:56 -07001213 /*
1214 * Shortcut the most recurring case: the user is in the dragging
1215 * state and he is moving his finger. We want to intercept this
1216 * motion.
1217 */
1218 final int action = ev.getAction();
1219 if ((action == MotionEvent.ACTION_MOVE) &&
1220 (mTouchState == TOUCH_STATE_SCROLLING)) {
1221 return true;
1222 }
1223
Winson Chung321e9ee2010-08-09 13:37:56 -07001224 switch (action & MotionEvent.ACTION_MASK) {
1225 case MotionEvent.ACTION_MOVE: {
1226 /*
1227 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1228 * whether the user has moved far enough from his original down touch.
1229 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001230 if (mActivePointerId != INVALID_POINTER) {
1231 determineScrollingStart(ev);
1232 break;
1233 }
1234 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1235 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1236 // i.e. fall through to the next case (don't break)
1237 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1238 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001239 }
1240
1241 case MotionEvent.ACTION_DOWN: {
1242 final float x = ev.getX();
1243 final float y = ev.getY();
1244 // Remember location of down touch
1245 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001246 mDownMotionY = y;
1247 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001248 mLastMotionX = x;
1249 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001250 float[] p = mapPointFromViewToParent(this, x, y);
1251 mParentDownMotionX = p[0];
1252 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001253 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001254 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001255 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001256
1257 // Determine if the down event is within the threshold to be an edge swipe
1258 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1259 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1260 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1261 mDownEventOnEdge = true;
1262 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001263
1264 /*
1265 * If being flinged and user touches the screen, initiate drag;
1266 * otherwise don't. mScroller.isFinished should be false when
1267 * being flinged.
1268 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001269 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001270 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1271 if (finishedScrolling) {
1272 mTouchState = TOUCH_STATE_REST;
1273 mScroller.abortAnimation();
1274 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001275 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1276 mTouchState = TOUCH_STATE_SCROLLING;
1277 } else {
1278 mTouchState = TOUCH_STATE_REST;
1279 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001280 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001281
Winson Chung86f77532010-08-24 11:08:22 -07001282 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001283 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001284 if (!DISABLE_TOUCH_SIDE_PAGES) {
1285 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1286 if (getChildCount() > 0) {
1287 if (hitsPreviousPage(x, y)) {
1288 mTouchState = TOUCH_STATE_PREV_PAGE;
1289 } else if (hitsNextPage(x, y)) {
1290 mTouchState = TOUCH_STATE_NEXT_PAGE;
1291 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001292 }
1293 }
1294 }
1295 break;
1296 }
1297
Winson Chung321e9ee2010-08-09 13:37:56 -07001298 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001299 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001300 resetTouchState();
1301 // Just intercept the touch event on up if we tap outside the strict viewport
1302 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1303 return true;
1304 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001305 break;
1306
1307 case MotionEvent.ACTION_POINTER_UP:
1308 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001309 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001310 break;
1311 }
1312
1313 /*
1314 * The only time we want to intercept motion events is if we are in the
1315 * drag mode.
1316 */
1317 return mTouchState != TOUCH_STATE_REST;
1318 }
1319
Adam Cohenf8d28232011-02-01 21:47:00 -08001320 protected void determineScrollingStart(MotionEvent ev) {
1321 determineScrollingStart(ev, 1.0f);
1322 }
1323
Winson Chung321e9ee2010-08-09 13:37:56 -07001324 /*
1325 * Determines if we should change the touch state to start scrolling after the
1326 * user moves their touch point too far.
1327 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001328 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001329 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001330 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001331 if (pointerIndex == -1) return;
1332
1333 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001334 final float x = ev.getX(pointerIndex);
1335 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001336 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1337
1338 // If we're only allowing edge swipes, we break out early if the down event wasn't
1339 // at the edge.
1340 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1341
Winson Chung321e9ee2010-08-09 13:37:56 -07001342 final int xDiff = (int) Math.abs(x - mLastMotionX);
1343 final int yDiff = (int) Math.abs(y - mLastMotionY);
1344
Adam Cohenf8d28232011-02-01 21:47:00 -08001345 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001346 boolean xPaged = xDiff > mPagingTouchSlop;
1347 boolean xMoved = xDiff > touchSlop;
1348 boolean yMoved = yDiff > touchSlop;
1349
Adam Cohenf8d28232011-02-01 21:47:00 -08001350 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001351 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001352 // Scroll if the user moved far enough along the X axis
1353 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001354 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001355 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001356 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001357 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001358 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1359 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001360 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001361 }
1362 }
1363
Adam Cohen7d30a372013-07-01 17:03:59 -07001364 protected float getMaxScrollProgress() {
1365 return 1.0f;
1366 }
1367
Adam Cohenf8d28232011-02-01 21:47:00 -08001368 protected void cancelCurrentPageLongPress() {
1369 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001370 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001371 // Try canceling the long press. It could also have been scheduled
1372 // by a distant descendant, so use the mAllowLongPress flag to block
1373 // everything
1374 final View currentPage = getPageAt(mCurrentPage);
1375 if (currentPage != null) {
1376 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001377 }
1378 }
1379 }
1380
Adam Cohen7d30a372013-07-01 17:03:59 -07001381 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1382 final int halfScreenSize = getViewportWidth() / 2;
1383
1384 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1385 screenCenter = Math.max(halfScreenSize, screenCenter);
1386
1387 return getScrollProgress(screenCenter, v, page);
1388 }
1389
Adam Cohenb5ba0972011-09-07 18:02:31 -07001390 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001391 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001392
Adam Cohen96d30a12013-07-16 18:13:21 -07001393 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001394 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001395
1396 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001397 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1398 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001399 return scrollProgress;
1400 }
1401
Adam Cohenedb40762013-07-18 16:45:45 -07001402 public int getScrollForPage(int index) {
1403 if (mPageScrolls == null || index >= mPageScrolls.length) {
1404 return 0;
1405 } else {
1406 return mPageScrolls[index];
1407 }
1408 }
1409
Adam Cohene0f66b52010-11-23 15:06:07 -08001410 // This curve determines how the effect of scrolling over the limits of the page dimishes
1411 // as the user pulls further and further from the bounds
1412 private float overScrollInfluenceCurve(float f) {
1413 f -= 1.0f;
1414 return f * f * f + 1.0f;
1415 }
1416
Adam Cohenb5ba0972011-09-07 18:02:31 -07001417 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001418 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001419
1420 // We want to reach the max over scroll effect when the user has
1421 // over scrolled half the size of the screen
1422 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1423
1424 if (f == 0) return;
1425
1426 // Clamp this factor, f, to -1 < f < 1
1427 if (Math.abs(f) >= 1) {
1428 f /= Math.abs(f);
1429 }
1430
1431 int overScrollAmount = (int) Math.round(f * screenSize);
1432 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001433 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001434 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001435 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001436 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001437 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001438 }
1439 invalidate();
1440 }
1441
1442 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001443 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001444
1445 float f = (amount / screenSize);
1446
1447 if (f == 0) return;
1448 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1449
Adam Cohen7bfc9792011-01-28 13:52:37 -08001450 // Clamp this factor, f, to -1 < f < 1
1451 if (Math.abs(f) >= 1) {
1452 f /= Math.abs(f);
1453 }
1454
Adam Cohene0f66b52010-11-23 15:06:07 -08001455 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001456 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001457 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001458 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001459 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001460 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001461 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001462 }
1463 invalidate();
1464 }
1465
Adam Cohenb5ba0972011-09-07 18:02:31 -07001466 protected void overScroll(float amount) {
1467 dampedOverScroll(amount);
1468 }
1469
Michael Jurkac5b262c2011-01-12 20:24:50 -08001470 protected float maxOverScroll() {
1471 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001472 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001473 float f = 1.0f;
1474 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1475 return OVERSCROLL_DAMP_FACTOR * f;
1476 }
1477
Winson Chung321e9ee2010-08-09 13:37:56 -07001478 @Override
1479 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001480 if (DISABLE_TOUCH_INTERACTION) {
1481 return false;
1482 }
1483
Winson Chung45e1d6e2010-11-09 17:19:49 -08001484 // Skip touch handling if there are no pages to swipe
1485 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1486
Michael Jurkab8f06722010-10-10 15:58:46 -07001487 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001488
1489 final int action = ev.getAction();
1490
1491 switch (action & MotionEvent.ACTION_MASK) {
1492 case MotionEvent.ACTION_DOWN:
1493 /*
1494 * If being flinged and user touches, stop the fling. isFinished
1495 * will be false if being flinged.
1496 */
1497 if (!mScroller.isFinished()) {
1498 mScroller.abortAnimation();
1499 }
1500
1501 // Remember where the motion event started
1502 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001503 mDownMotionY = mLastMotionY = ev.getY();
1504 mDownScrollX = getScrollX();
1505 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1506 mParentDownMotionX = p[0];
1507 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001508 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001509 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001510 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001511
1512 // Determine if the down event is within the threshold to be an edge swipe
1513 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1514 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1515 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1516 mDownEventOnEdge = true;
1517 }
1518
Michael Jurka0142d492010-08-25 17:46:15 -07001519 if (mTouchState == TOUCH_STATE_SCROLLING) {
1520 pageBeginMoving();
1521 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001522 break;
1523
1524 case MotionEvent.ACTION_MOVE:
1525 if (mTouchState == TOUCH_STATE_SCROLLING) {
1526 // Scroll to follow the motion event
1527 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001528
1529 if (pointerIndex == -1) return true;
1530
Winson Chung321e9ee2010-08-09 13:37:56 -07001531 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001532 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001533
Adam Cohenaefd4e12011-02-14 16:39:38 -08001534 mTotalMotionX += Math.abs(deltaX);
1535
Winson Chungc0844aa2011-02-02 15:25:58 -08001536 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1537 // keep the remainder because we are actually testing if we've moved from the last
1538 // scrolled position (which is discrete).
1539 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001540 mTouchX += deltaX;
1541 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1542 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001543 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001544 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001545 } else {
1546 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001547 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001548 mLastMotionX = x;
1549 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001550 } else {
1551 awakenScrollBars();
1552 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001553 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1554 // Update the last motion position
1555 mLastMotionX = ev.getX();
1556 mLastMotionY = ev.getY();
1557
1558 // Update the parent down so that our zoom animations take this new movement into
1559 // account
1560 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1561 mParentDownMotionX = pt[0];
1562 mParentDownMotionY = pt[1];
1563 updateDragViewTranslationDuringDrag();
1564
1565 // Find the closest page to the touch point
1566 final int dragViewIndex = indexOfChild(mDragView);
1567 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1568 getViewportWidth());
1569 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1570 + bufferSize);
1571 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1572 - bufferSize);
1573
1574 // Change the drag view if we are hovering over the drop target
1575 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1576 (int) mParentDownMotionX, (int) mParentDownMotionY);
1577 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1578
1579 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1580 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1581 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1582 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1583 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1584 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1585
1586 float parentX = mParentDownMotionX;
1587 int pageIndexToSnapTo = -1;
1588 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1589 pageIndexToSnapTo = dragViewIndex - 1;
1590 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1591 pageIndexToSnapTo = dragViewIndex + 1;
1592 }
1593
1594 final int pageUnderPointIndex = pageIndexToSnapTo;
1595 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1596 mTempVisiblePagesRange[0] = 0;
1597 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07001598 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001599 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1600 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1601 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1602 mSidePageHoverIndex = pageUnderPointIndex;
1603 mSidePageHoverRunnable = new Runnable() {
1604 @Override
1605 public void run() {
1606 // Update the down scroll position to account for the fact that the
1607 // current page is moved
Adam Cohenedb40762013-07-18 16:45:45 -07001608 mDownScrollX = getScrollForPage(pageUnderPointIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001609
1610 // Setup the scroll to the correct page before we swap the views
1611 snapToPage(pageUnderPointIndex);
1612
1613 // For each of the pages between the paged view and the drag view,
1614 // animate them from the previous position to the new position in
1615 // the layout (as a result of the drag view moving in the layout)
1616 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1617 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1618 dragViewIndex + 1 : pageUnderPointIndex;
1619 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1620 dragViewIndex - 1 : pageUnderPointIndex;
1621 for (int i = lowerIndex; i <= upperIndex; ++i) {
1622 View v = getChildAt(i);
1623 // dragViewIndex < pageUnderPointIndex, so after we remove the
1624 // drag view all subsequent views to pageUnderPointIndex will
1625 // shift down.
1626 int oldX = getViewportOffsetX() + getChildOffset(i);
1627 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1628
1629 // Animate the view translation from its old position to its new
1630 // position
1631 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1632 if (anim != null) {
1633 anim.cancel();
1634 }
1635
1636 v.setTranslationX(oldX - newX);
1637 anim = new AnimatorSet();
1638 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1639 anim.playTogether(
1640 ObjectAnimator.ofFloat(v, "translationX", 0f));
1641 anim.start();
1642 v.setTag(anim);
1643 }
1644
1645 removeView(mDragView);
1646 onRemoveView(mDragView, false);
1647 addView(mDragView, pageUnderPointIndex);
1648 onAddView(mDragView, pageUnderPointIndex);
1649 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001650 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001651 }
1652 };
1653 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1654 }
1655 } else {
1656 removeCallbacks(mSidePageHoverRunnable);
1657 mSidePageHoverIndex = -1;
1658 }
Adam Cohen564976a2010-10-13 18:52:07 -07001659 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001660 determineScrollingStart(ev);
1661 }
1662 break;
1663
1664 case MotionEvent.ACTION_UP:
1665 if (mTouchState == TOUCH_STATE_SCROLLING) {
1666 final int activePointerId = mActivePointerId;
1667 final int pointerIndex = ev.findPointerIndex(activePointerId);
1668 final float x = ev.getX(pointerIndex);
1669 final VelocityTracker velocityTracker = mVelocityTracker;
1670 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1671 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001672 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001673 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001674 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1675 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001676
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001677 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1678
Adam Cohen00481b32011-11-18 12:03:48 -08001679 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001680 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001681
Adam Cohenaefd4e12011-02-14 16:39:38 -08001682 // In the case that the page is moved far to one direction and then is flung
1683 // in the opposite direction, we use a threshold to determine whether we should
1684 // just return to the starting page, or if we should skip one further.
1685 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001686 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001687 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001688 returnToOriginalPage = true;
1689 }
1690
Adam Cohenaefd4e12011-02-14 16:39:38 -08001691 int finalPage;
1692 // We give flings precedence over large moves, which is why we short-circuit our
1693 // test for a large move if a fling has been registered. That is, a large
1694 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001695 final boolean isRtl = isLayoutRtl();
1696 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1697 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1698 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1699 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001700 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1701 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001702 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1703 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001704 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001705 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1706 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001707 } else {
1708 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001709 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001710 // at this point we have not moved beyond the touch slop
1711 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1712 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001713 int nextPage = Math.max(0, mCurrentPage - 1);
1714 if (nextPage != mCurrentPage) {
1715 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001716 } else {
1717 snapToDestination();
1718 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001719 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001720 // at this point we have not moved beyond the touch slop
1721 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1722 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001723 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1724 if (nextPage != mCurrentPage) {
1725 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001726 } else {
1727 snapToDestination();
1728 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001729 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1730 // Update the last motion position
1731 mLastMotionX = ev.getX();
1732 mLastMotionY = ev.getY();
1733
1734 // Update the parent down so that our zoom animations take this new movement into
1735 // account
1736 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1737 mParentDownMotionX = pt[0];
1738 mParentDownMotionY = pt[1];
1739 updateDragViewTranslationDuringDrag();
1740 boolean handledFling = false;
1741 if (!DISABLE_FLING_TO_DELETE) {
1742 // Check the velocity and see if we are flinging-to-delete
1743 PointF flingToDeleteVector = isFlingingToDelete();
1744 if (flingToDeleteVector != null) {
1745 onFlingToDelete(flingToDeleteVector);
1746 handledFling = true;
1747 }
1748 }
1749 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1750 (int) mParentDownMotionY)) {
1751 onDropToDelete();
1752 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001753 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001754 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001755 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001756
1757 // Remove the callback to wait for the side page hover timeout
1758 removeCallbacks(mSidePageHoverRunnable);
1759 // End any intermediate reordering states
1760 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001761 break;
1762
1763 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001764 if (mTouchState == TOUCH_STATE_SCROLLING) {
1765 snapToDestination();
1766 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001767 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001768 break;
1769
1770 case MotionEvent.ACTION_POINTER_UP:
1771 onSecondaryPointerUp(ev);
1772 break;
1773 }
1774
1775 return true;
1776 }
1777
Adam Cohen7d30a372013-07-01 17:03:59 -07001778 public void onFlingToDelete(View v) {}
1779 public void onRemoveView(View v, boolean deletePermanently) {}
1780 public void onRemoveViewAnimationCompleted() {}
1781 public void onAddView(View v, int index) {}
1782
1783 private void resetTouchState() {
1784 releaseVelocityTracker();
1785 endReordering();
1786 mTouchState = TOUCH_STATE_REST;
1787 mActivePointerId = INVALID_POINTER;
1788 mDownEventOnEdge = false;
1789 }
1790
1791 protected void onUnhandledTap(MotionEvent ev) {}
1792
Winson Chung185d7162011-02-28 13:47:29 -08001793 @Override
1794 public boolean onGenericMotionEvent(MotionEvent event) {
1795 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1796 switch (event.getAction()) {
1797 case MotionEvent.ACTION_SCROLL: {
1798 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1799 final float vscroll;
1800 final float hscroll;
1801 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1802 vscroll = 0;
1803 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1804 } else {
1805 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1806 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1807 }
1808 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001809 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1810 : (hscroll > 0 || vscroll > 0);
1811 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001812 scrollRight();
1813 } else {
1814 scrollLeft();
1815 }
1816 return true;
1817 }
1818 }
1819 }
1820 }
1821 return super.onGenericMotionEvent(event);
1822 }
1823
Michael Jurkab8f06722010-10-10 15:58:46 -07001824 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1825 if (mVelocityTracker == null) {
1826 mVelocityTracker = VelocityTracker.obtain();
1827 }
1828 mVelocityTracker.addMovement(ev);
1829 }
1830
1831 private void releaseVelocityTracker() {
1832 if (mVelocityTracker != null) {
1833 mVelocityTracker.recycle();
1834 mVelocityTracker = null;
1835 }
1836 }
1837
Winson Chung321e9ee2010-08-09 13:37:56 -07001838 private void onSecondaryPointerUp(MotionEvent ev) {
1839 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1840 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1841 final int pointerId = ev.getPointerId(pointerIndex);
1842 if (pointerId == mActivePointerId) {
1843 // This was our active pointer going up. Choose a new
1844 // active pointer and adjust accordingly.
1845 // TODO: Make this decision more intelligent.
1846 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1847 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1848 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001849 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001850 mActivePointerId = ev.getPointerId(newPointerIndex);
1851 if (mVelocityTracker != null) {
1852 mVelocityTracker.clear();
1853 }
1854 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001855 }
1856
Winson Chung321e9ee2010-08-09 13:37:56 -07001857 @Override
1858 public void requestChildFocus(View child, View focused) {
1859 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001860 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001861 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001862 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001863 }
1864 }
1865
Winson Chung1908d072011-02-24 18:09:44 -08001866 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001867 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001868 }
1869
Adam Cohen7d30a372013-07-01 17:03:59 -07001870 int getPageNearestToPoint(float x) {
1871 int index = 0;
1872 for (int i = 0; i < getChildCount(); ++i) {
1873 if (x < getChildAt(i).getRight() - getScrollX()) {
1874 return index;
1875 } else {
1876 index++;
1877 }
1878 }
1879 return Math.min(index, getChildCount() - 1);
1880 }
1881
Adam Cohend19d3ca2010-09-15 14:43:42 -07001882 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001883 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001884 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001885 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001886 final int childCount = getChildCount();
1887 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001888 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001889 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001890 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001891 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001892 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1893 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1894 minDistanceFromScreenCenter = distanceFromScreenCenter;
1895 minDistanceFromScreenCenterIndex = i;
1896 }
1897 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001898 return minDistanceFromScreenCenterIndex;
1899 }
1900
1901 protected void snapToDestination() {
1902 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001903 }
1904
Adam Cohene0f66b52010-11-23 15:06:07 -08001905 private static class ScrollInterpolator implements Interpolator {
1906 public ScrollInterpolator() {
1907 }
1908
1909 public float getInterpolation(float t) {
1910 t -= 1.0f;
1911 return t*t*t*t*t + 1;
1912 }
1913 }
1914
1915 // We want the duration of the page snap animation to be influenced by the distance that
1916 // the screen has to travel, however, we don't want this duration to be effected in a
1917 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1918 // of travel has on the overall snap duration.
1919 float distanceInfluenceForSnapDuration(float f) {
1920 f -= 0.5f; // center the values about 0.
1921 f *= 0.3f * Math.PI / 2.0f;
1922 return (float) Math.sin(f);
1923 }
1924
Michael Jurka0142d492010-08-25 17:46:15 -07001925 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001926 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001927 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001928
Adam Cohenedb40762013-07-18 16:45:45 -07001929 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08001930 int delta = newX - mUnboundedScrollX;
1931 int duration = 0;
1932
Adam Cohen265b9a62011-12-07 14:37:18 -08001933 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001934 // If the velocity is low enough, then treat this more as an automatic page advance
1935 // as opposed to an apparent physical response to flinging
1936 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1937 return;
1938 }
1939
1940 // Here we compute a "distance" that will be used in the computation of the overall
1941 // snap duration. This is a function of the actual distance that needs to be traveled;
1942 // we keep this value close to half screen size in order to reduce the variance in snap
1943 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001944 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001945 float distance = halfScreenSize + halfScreenSize *
1946 distanceInfluenceForSnapDuration(distanceRatio);
1947
1948 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001949 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001950
1951 // we want the page's snap velocity to approximately match the velocity at which the
1952 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001953 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1954 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001955
1956 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001957 }
1958
1959 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001960 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001961 }
1962
Adam Cohen7d30a372013-07-01 17:03:59 -07001963 protected void snapToPageImmediately(int whichPage) {
1964 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1965 }
1966
Michael Jurka0142d492010-08-25 17:46:15 -07001967 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001968 snapToPage(whichPage, duration, false);
1969 }
1970
1971 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07001972 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07001973
Adam Cohenedb40762013-07-18 16:45:45 -07001974 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08001975 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001976 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07001977 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07001978 }
1979
1980 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001981 snapToPage(whichPage, delta, duration, false);
1982 }
Michael Jurka0142d492010-08-25 17:46:15 -07001983
Adam Cohen7d30a372013-07-01 17:03:59 -07001984 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
1985 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07001986 View focusedChild = getFocusedChild();
1987 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07001988 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07001989 focusedChild.clearFocus();
1990 }
1991
1992 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001993 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07001994 if (immediate) {
1995 duration = 0;
1996 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001997 duration = Math.abs(delta);
1998 }
1999
2000 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002001 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002002
Michael Jurka0142d492010-08-25 17:46:15 -07002003 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002004
2005 // Trigger a compute() to finish switching pages if necessary
2006 if (immediate) {
2007 computeScroll();
2008 }
2009
2010 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002011 invalidate();
2012 }
2013
Winson Chung321e9ee2010-08-09 13:37:56 -07002014 public void scrollLeft() {
2015 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002016 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002017 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002018 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002019 }
2020 }
2021
2022 public void scrollRight() {
2023 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002024 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002025 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002026 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002027 }
2028 }
2029
Winson Chung86f77532010-08-24 11:08:22 -07002030 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002031 int result = -1;
2032 if (v != null) {
2033 ViewParent vp = v.getParent();
2034 int count = getChildCount();
2035 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002036 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002037 return i;
2038 }
2039 }
2040 }
2041 return result;
2042 }
2043
2044 /**
2045 * @return True is long presses are still allowed for the current touch
2046 */
2047 public boolean allowLongPress() {
2048 return mAllowLongPress;
2049 }
2050
Michael Jurka0142d492010-08-25 17:46:15 -07002051 /**
2052 * Set true to allow long-press events to be triggered, usually checked by
2053 * {@link Launcher} to accept or block dpad-initiated long-presses.
2054 */
2055 public void setAllowLongPress(boolean allowLongPress) {
2056 mAllowLongPress = allowLongPress;
2057 }
2058
Winson Chung321e9ee2010-08-09 13:37:56 -07002059 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002060 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002061
2062 SavedState(Parcelable superState) {
2063 super(superState);
2064 }
2065
2066 private SavedState(Parcel in) {
2067 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002068 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002069 }
2070
2071 @Override
2072 public void writeToParcel(Parcel out, int flags) {
2073 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002074 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002075 }
2076
2077 public static final Parcelable.Creator<SavedState> CREATOR =
2078 new Parcelable.Creator<SavedState>() {
2079 public SavedState createFromParcel(Parcel in) {
2080 return new SavedState(in);
2081 }
2082
2083 public SavedState[] newArray(int size) {
2084 return new SavedState[size];
2085 }
2086 };
2087 }
2088
Winson Chungf314b0e2011-08-16 11:54:27 -07002089 protected void loadAssociatedPages(int page) {
2090 loadAssociatedPages(page, false);
2091 }
2092 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002093 if (mContentIsRefreshable) {
2094 final int count = getChildCount();
2095 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002096 int lowerPageBound = getAssociatedLowerPageBound(page);
2097 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002098 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2099 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002100 // First, clear any pages that should no longer be loaded
2101 for (int i = 0; i < count; ++i) {
2102 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002103 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002104 if (layout.getPageChildCount() > 0) {
2105 layout.removeAllViewsOnPage();
2106 }
2107 mDirtyPageContent.set(i, true);
2108 }
2109 }
2110 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002111 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002112 if ((i != page) && immediateAndOnly) {
2113 continue;
2114 }
Michael Jurka0142d492010-08-25 17:46:15 -07002115 if (lowerPageBound <= i && i <= upperPageBound) {
2116 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002117 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002118 mDirtyPageContent.set(i, false);
2119 }
Winson Chung86f77532010-08-24 11:08:22 -07002120 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002121 }
2122 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002123 }
2124 }
2125
Winson Chunge3193b92010-09-10 11:44:42 -07002126 protected int getAssociatedLowerPageBound(int page) {
2127 return Math.max(0, page - 1);
2128 }
2129 protected int getAssociatedUpperPageBound(int page) {
2130 final int count = getChildCount();
2131 return Math.min(page + 1, count - 1);
2132 }
2133
Winson Chung86f77532010-08-24 11:08:22 -07002134 /**
2135 * This method is called ONLY to synchronize the number of pages that the paged view has.
2136 * To actually fill the pages with information, implement syncPageItems() below. It is
2137 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2138 * and therefore, individual page items do not need to be updated in this method.
2139 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002140 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002141
2142 /**
2143 * This method is called to synchronize the items that are on a particular page. If views on
2144 * the page can be reused, then they should be updated within this method.
2145 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002146 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002147
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002148 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002149 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002150 }
2151 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002152 invalidatePageData(currentPage, false);
2153 }
2154 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002155 if (!mIsDataReady) {
2156 return;
2157 }
2158
Michael Jurka0142d492010-08-25 17:46:15 -07002159 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002160 // Force all scrolling-related behavior to end
2161 mScroller.forceFinished(true);
2162 mNextPage = INVALID_PAGE;
2163
Michael Jurka0142d492010-08-25 17:46:15 -07002164 // Update all the pages
2165 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002166
Winson Chung5a808352011-06-27 19:08:49 -07002167 // We must force a measure after we've loaded the pages to update the content width and
2168 // to determine the full scroll width
2169 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2170 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2171
2172 // Set a new page as the current page if necessary
2173 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002174 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002175 }
2176
Michael Jurka0142d492010-08-25 17:46:15 -07002177 // Mark each of the pages as dirty
2178 final int count = getChildCount();
2179 mDirtyPageContent.clear();
2180 for (int i = 0; i < count; ++i) {
2181 mDirtyPageContent.add(true);
2182 }
2183
2184 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002185 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002186 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002187 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002188 }
Winson Chung007c6982011-06-14 13:27:53 -07002189
Adam Cohen7d30a372013-07-01 17:03:59 -07002190 // Animate the drag view back to the original position
2191 void animateDragViewToOriginalPosition() {
2192 if (mDragView != null) {
2193 AnimatorSet anim = new AnimatorSet();
2194 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2195 anim.playTogether(
2196 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2197 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2198 anim.addListener(new AnimatorListenerAdapter() {
2199 @Override
2200 public void onAnimationEnd(Animator animation) {
2201 onPostReorderingAnimationCompleted();
2202 }
2203 });
2204 anim.start();
2205 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002206 }
2207
Adam Cohen7d30a372013-07-01 17:03:59 -07002208 // "Zooms out" the PagedView to reveal more side pages
2209 protected boolean zoomOut() {
2210 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2211 mZoomInOutAnim.cancel();
2212 }
2213
2214 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2215 mZoomInOutAnim = new AnimatorSet();
2216 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2217 mZoomInOutAnim.playTogether(
2218 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2219 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2220 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2221 @Override
2222 public void onAnimationStart(Animator animation) {
2223 // Show the delete drop target
2224 if (mDeleteDropTarget != null) {
2225 mDeleteDropTarget.setVisibility(View.VISIBLE);
2226 mDeleteDropTarget.animate().alpha(1f)
2227 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2228 .setListener(new AnimatorListenerAdapter() {
2229 @Override
2230 public void onAnimationStart(Animator animation) {
2231 mDeleteDropTarget.setAlpha(0f);
2232 }
2233 });
2234 }
2235 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002236 @Override
2237 public void onAnimationEnd(Animator animation) {
2238 // Update the visible pages
2239 invalidate();
2240 }
Adam Cohen7d30a372013-07-01 17:03:59 -07002241 });
2242 mZoomInOutAnim.start();
2243 return true;
2244 }
2245 return false;
2246 }
2247
2248 protected void onStartReordering() {
2249 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2250 mTouchState = TOUCH_STATE_REORDERING;
2251 mIsReordering = true;
2252
2253 // Mark all the non-widget pages as invisible
Winson Chungc9ca2982013-07-19 12:07:38 -07002254 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002255 for (int i = 0; i < getPageCount(); ++i) {
2256 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2257 getPageAt(i).setAlpha(0f);
2258 }
2259 }
2260
2261 // We must invalidate to trigger a redraw to update the layers such that the drag view
2262 // is always drawn on top
2263 invalidate();
2264 }
2265
2266 private void onPostReorderingAnimationCompleted() {
2267 // Trigger the callback when reordering has settled
2268 --mPostReorderingPreZoomInRemainingAnimationCount;
2269 if (mPostReorderingPreZoomInRunnable != null &&
2270 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2271 mPostReorderingPreZoomInRunnable.run();
2272 mPostReorderingPreZoomInRunnable = null;
2273 }
2274 }
2275
2276 protected void onEndReordering() {
2277 mIsReordering = false;
2278
2279 // Mark all the non-widget pages as visible again
Winson Chungc9ca2982013-07-19 12:07:38 -07002280 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002281 for (int i = 0; i < getPageCount(); ++i) {
2282 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2283 getPageAt(i).setAlpha(1f);
2284 }
2285 }
2286 }
2287
2288 public boolean startReordering() {
2289 int dragViewIndex = getPageNearestToCenterOfScreen();
2290 mTempVisiblePagesRange[0] = 0;
2291 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07002292 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002293 mReorderingStarted = true;
2294
2295 // Check if we are within the reordering range
2296 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2297 dragViewIndex <= mTempVisiblePagesRange[1]) {
2298 if (zoomOut()) {
2299 // Find the drag view under the pointer
2300 mDragView = getChildAt(dragViewIndex);
2301
2302 onStartReordering();
2303 }
2304 return true;
2305 }
2306 return false;
2307 }
2308
2309 boolean isReordering(boolean testTouchState) {
2310 boolean state = mIsReordering;
2311 if (testTouchState) {
2312 state &= (mTouchState == TOUCH_STATE_REORDERING);
2313 }
2314 return state;
2315 }
2316 void endReordering() {
2317 // For simplicity, we call endReordering sometimes even if reordering was never started.
2318 // In that case, we don't want to do anything.
2319 if (!mReorderingStarted) return;
2320 mReorderingStarted = false;
2321
2322 // If we haven't flung-to-delete the current child, then we just animate the drag view
2323 // back into position
2324 final Runnable onCompleteRunnable = new Runnable() {
2325 @Override
2326 public void run() {
2327 onEndReordering();
2328 }
2329 };
2330 if (!mDeferringForDelete) {
2331 mPostReorderingPreZoomInRunnable = new Runnable() {
2332 public void run() {
2333 zoomIn(onCompleteRunnable);
2334 };
2335 };
2336
2337 mPostReorderingPreZoomInRemainingAnimationCount =
2338 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2339 // Snap to the current page
2340 snapToPage(indexOfChild(mDragView), 0);
2341 // Animate the drag view back to the front position
2342 animateDragViewToOriginalPosition();
2343 } else {
2344 // Handled in post-delete-animation-callbacks
2345 }
2346 }
2347
2348 // "Zooms in" the PagedView to highlight the current page
2349 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2350 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2351 mZoomInOutAnim.cancel();
2352 }
2353 if (getScaleX() < 1f || getScaleY() < 1f) {
2354 mZoomInOutAnim = new AnimatorSet();
2355 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2356 mZoomInOutAnim.playTogether(
2357 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2358 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2359 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2360 @Override
2361 public void onAnimationStart(Animator animation) {
2362 // Hide the delete drop target
2363 if (mDeleteDropTarget != null) {
2364 mDeleteDropTarget.animate().alpha(0f)
2365 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2366 .setListener(new AnimatorListenerAdapter() {
2367 @Override
2368 public void onAnimationEnd(Animator animation) {
2369 mDeleteDropTarget.setVisibility(View.GONE);
2370 }
2371 });
2372 }
2373 }
2374 @Override
2375 public void onAnimationCancel(Animator animation) {
2376 mDragView = null;
2377 }
2378 @Override
2379 public void onAnimationEnd(Animator animation) {
2380 mDragView = null;
2381 if (onCompleteRunnable != null) {
2382 onCompleteRunnable.run();
2383 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002384 // Update the visible pages
2385 invalidate();
Adam Cohen7d30a372013-07-01 17:03:59 -07002386 }
2387 });
2388 mZoomInOutAnim.start();
2389 return true;
2390 } else {
2391 if (onCompleteRunnable != null) {
2392 onCompleteRunnable.run();
2393 }
2394 }
2395 return false;
2396 }
2397
2398 /*
2399 * Flinging to delete - IN PROGRESS
2400 */
2401 private PointF isFlingingToDelete() {
2402 ViewConfiguration config = ViewConfiguration.get(getContext());
2403 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2404
2405 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2406 // Do a quick dot product test to ensure that we are flinging upwards
2407 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2408 mVelocityTracker.getYVelocity());
2409 PointF upVec = new PointF(0f, -1f);
2410 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2411 (vel.length() * upVec.length()));
2412 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2413 return vel;
2414 }
2415 }
2416 return null;
2417 }
2418
2419 /**
2420 * Creates an animation from the current drag view along its current velocity vector.
2421 * For this animation, the alpha runs for a fixed duration and we update the position
2422 * progressively.
2423 */
2424 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2425 private View mDragView;
2426 private PointF mVelocity;
2427 private Rect mFrom;
2428 private long mPrevTime;
2429 private float mFriction;
2430
2431 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2432
2433 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2434 long startTime, float friction) {
2435 mDragView = dragView;
2436 mVelocity = vel;
2437 mFrom = from;
2438 mPrevTime = startTime;
2439 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2440 }
2441
2442 @Override
2443 public void onAnimationUpdate(ValueAnimator animation) {
2444 float t = ((Float) animation.getAnimatedValue()).floatValue();
2445 long curTime = AnimationUtils.currentAnimationTimeMillis();
2446
2447 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2448 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2449
2450 mDragView.setTranslationX(mFrom.left);
2451 mDragView.setTranslationY(mFrom.top);
2452 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2453
2454 mVelocity.x *= mFriction;
2455 mVelocity.y *= mFriction;
2456 mPrevTime = curTime;
2457 }
2458 };
2459
2460 private static final int ANIM_TAG_KEY = 100;
2461
2462 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2463 return new Runnable() {
2464 @Override
2465 public void run() {
2466 int dragViewIndex = indexOfChild(dragView);
2467
2468 // For each of the pages around the drag view, animate them from the previous
2469 // position to the new position in the layout (as a result of the drag view moving
2470 // in the layout)
2471 // NOTE: We can make an assumption here because we have side-bound pages that we
2472 // will always have pages to animate in from the left
Winson Chungc9ca2982013-07-19 12:07:38 -07002473 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002474 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2475 boolean slideFromLeft = (isLastWidgetPage ||
2476 dragViewIndex > mTempVisiblePagesRange[0]);
2477
2478 // Setup the scroll to the correct page before we swap the views
2479 if (slideFromLeft) {
2480 snapToPageImmediately(dragViewIndex - 1);
2481 }
2482
2483 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2484 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2485 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2486 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2487 ArrayList<Animator> animations = new ArrayList<Animator>();
2488 for (int i = lowerIndex; i <= upperIndex; ++i) {
2489 View v = getChildAt(i);
2490 // dragViewIndex < pageUnderPointIndex, so after we remove the
2491 // drag view all subsequent views to pageUnderPointIndex will
2492 // shift down.
2493 int oldX = 0;
2494 int newX = 0;
2495 if (slideFromLeft) {
2496 if (i == 0) {
2497 // Simulate the page being offscreen with the page spacing
2498 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2499 - mPageSpacing;
2500 } else {
2501 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2502 }
2503 newX = getViewportOffsetX() + getChildOffset(i);
2504 } else {
2505 oldX = getChildOffset(i) - getChildOffset(i - 1);
2506 newX = 0;
2507 }
2508
2509 // Animate the view translation from its old position to its new
2510 // position
2511 AnimatorSet anim = (AnimatorSet) v.getTag();
2512 if (anim != null) {
2513 anim.cancel();
2514 }
2515
2516 // Note: Hacky, but we want to skip any optimizations to not draw completely
2517 // hidden views
2518 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2519 v.setTranslationX(oldX - newX);
2520 anim = new AnimatorSet();
2521 anim.playTogether(
2522 ObjectAnimator.ofFloat(v, "translationX", 0f),
2523 ObjectAnimator.ofFloat(v, "alpha", 1f));
2524 animations.add(anim);
2525 v.setTag(ANIM_TAG_KEY, anim);
2526 }
2527
2528 AnimatorSet slideAnimations = new AnimatorSet();
2529 slideAnimations.playTogether(animations);
2530 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2531 slideAnimations.addListener(new AnimatorListenerAdapter() {
2532 @Override
2533 public void onAnimationEnd(Animator animation) {
2534 final Runnable onCompleteRunnable = new Runnable() {
2535 @Override
2536 public void run() {
2537 mDeferringForDelete = false;
2538 onEndReordering();
2539 onRemoveViewAnimationCompleted();
2540 }
2541 };
2542 zoomIn(onCompleteRunnable);
2543 }
2544 });
2545 slideAnimations.start();
2546
2547 removeView(dragView);
2548 onRemoveView(dragView, true);
2549 }
2550 };
2551 }
2552
2553 public void onFlingToDelete(PointF vel) {
2554 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2555
2556 // NOTE: Because it takes time for the first frame of animation to actually be
2557 // called and we expect the animation to be a continuation of the fling, we have
2558 // to account for the time that has elapsed since the fling finished. And since
2559 // we don't have a startDelay, we will always get call to update when we call
2560 // start() (which we want to ignore).
2561 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2562 private int mCount = -1;
2563 private long mStartTime;
2564 private float mOffset;
2565 /* Anonymous inner class ctor */ {
2566 mStartTime = startTime;
2567 }
2568
2569 @Override
2570 public float getInterpolation(float t) {
2571 if (mCount < 0) {
2572 mCount++;
2573 } else if (mCount == 0) {
2574 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2575 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2576 mCount++;
2577 }
2578 return Math.min(1f, mOffset + t);
2579 }
2580 };
2581
2582 final Rect from = new Rect();
2583 final View dragView = mDragView;
2584 from.left = (int) dragView.getTranslationX();
2585 from.top = (int) dragView.getTranslationY();
2586 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2587 from, startTime, FLING_TO_DELETE_FRICTION);
2588
2589 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2590
2591 // Create and start the animation
2592 ValueAnimator mDropAnim = new ValueAnimator();
2593 mDropAnim.setInterpolator(tInterpolator);
2594 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2595 mDropAnim.setFloatValues(0f, 1f);
2596 mDropAnim.addUpdateListener(updateCb);
2597 mDropAnim.addListener(new AnimatorListenerAdapter() {
2598 public void onAnimationEnd(Animator animation) {
2599 onAnimationEndRunnable.run();
2600 }
2601 });
2602 mDropAnim.start();
2603 mDeferringForDelete = true;
2604 }
2605
2606 /* Drag to delete */
2607 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2608 if (mDeleteDropTarget != null) {
2609 mAltTmpRect.set(0, 0, 0, 0);
2610 View parent = (View) mDeleteDropTarget.getParent();
2611 if (parent != null) {
2612 parent.getGlobalVisibleRect(mAltTmpRect);
2613 }
2614 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2615 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2616 return mTmpRect.contains(x, y);
2617 }
2618 return false;
2619 }
2620
2621 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2622
2623 private void onDropToDelete() {
2624 final View dragView = mDragView;
2625
2626 final float toScale = 0f;
2627 final float toAlpha = 0f;
2628
2629 // Create and start the complex animation
2630 ArrayList<Animator> animations = new ArrayList<Animator>();
2631 AnimatorSet motionAnim = new AnimatorSet();
2632 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2633 motionAnim.playTogether(
2634 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2635 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2636 animations.add(motionAnim);
2637
2638 AnimatorSet alphaAnim = new AnimatorSet();
2639 alphaAnim.setInterpolator(new LinearInterpolator());
2640 alphaAnim.playTogether(
2641 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2642 animations.add(alphaAnim);
2643
2644 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2645
2646 AnimatorSet anim = new AnimatorSet();
2647 anim.playTogether(animations);
2648 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2649 anim.addListener(new AnimatorListenerAdapter() {
2650 public void onAnimationEnd(Animator animation) {
2651 onAnimationEndRunnable.run();
2652 }
2653 });
2654 anim.start();
2655
2656 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002657 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002658
2659 /* Accessibility */
2660 @Override
2661 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2662 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002663 info.setScrollable(getPageCount() > 1);
2664 if (getCurrentPage() < getPageCount() - 1) {
2665 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2666 }
2667 if (getCurrentPage() > 0) {
2668 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2669 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002670 }
2671
2672 @Override
2673 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2674 super.onInitializeAccessibilityEvent(event);
2675 event.setScrollable(true);
2676 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2677 event.setFromIndex(mCurrentPage);
2678 event.setToIndex(mCurrentPage);
2679 event.setItemCount(getChildCount());
2680 }
2681 }
2682
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002683 @Override
2684 public boolean performAccessibilityAction(int action, Bundle arguments) {
2685 if (super.performAccessibilityAction(action, arguments)) {
2686 return true;
2687 }
2688 switch (action) {
2689 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2690 if (getCurrentPage() < getPageCount() - 1) {
2691 scrollRight();
2692 return true;
2693 }
2694 } break;
2695 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2696 if (getCurrentPage() > 0) {
2697 scrollLeft();
2698 return true;
2699 }
2700 } break;
2701 }
2702 return false;
2703 }
2704
Adam Cohen0ffac432013-07-10 11:19:26 -07002705 protected String getCurrentPageDescription() {
2706 return String.format(getContext().getString(R.string.default_scroll_format),
2707 getNextPage() + 1, getChildCount());
2708 }
2709
Winson Chungd11265e2011-08-30 13:37:23 -07002710 @Override
2711 public boolean onHoverEvent(android.view.MotionEvent event) {
2712 return true;
2713 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002714}