blob: ed88ea90dadd092e805bda600390021e81f33bd0 [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;
Winson Chung8c87cd82013-07-23 16:20:10 -0700107 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700108 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700109
Michael Jurka0142d492010-08-25 17:46:15 -0700110 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800111 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700112 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700113 private VelocityTracker mVelocityTracker;
114
Adam Cohen7d30a372013-07-01 17:03:59 -0700115 private float mParentDownMotionX;
116 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700117 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700118 private float mDownMotionY;
119 private float mDownScrollX;
Michael Jurka7426c422010-11-11 15:23:47 -0800120 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800121 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800122 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800123 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700124 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700125
126 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700127
Michael Jurka0142d492010-08-25 17:46:15 -0700128 protected final static int TOUCH_STATE_REST = 0;
129 protected final static int TOUCH_STATE_SCROLLING = 1;
130 protected final static int TOUCH_STATE_PREV_PAGE = 2;
131 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700132 protected final static int TOUCH_STATE_REORDERING = 4;
133
Adam Cohene45440e2010-10-14 18:33:38 -0700134 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700135
Michael Jurka0142d492010-08-25 17:46:15 -0700136 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700137 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700138
Michael Jurka0142d492010-08-25 17:46:15 -0700139 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700140
Michael Jurka7426c422010-11-11 15:23:47 -0800141 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700142 private int mPagingTouchSlop;
143 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700144 protected int mPageSpacing;
145 protected int mPageLayoutPaddingTop;
146 protected int mPageLayoutPaddingBottom;
147 protected int mPageLayoutPaddingLeft;
148 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700149 protected int mPageLayoutWidthGap;
150 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700151 protected int mCellCountX = 0;
152 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700153 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800154 protected boolean mAllowOverScroll = true;
155 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800156 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700157 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700158
Michael Jurka8b805b12012-04-18 14:23:14 -0700159 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800160 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
161 // the screens from continuing to translate beyond the normal bounds.
162 protected int mOverScrollX;
163
Michael Jurka5f1c5092010-09-03 14:15:02 -0700164 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700165
Michael Jurka5f1c5092010-09-03 14:15:02 -0700166 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700167
Winson Chung86f77532010-08-24 11:08:22 -0700168 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700169
Michael Jurkae326f182011-11-21 14:05:46 -0800170 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700171
Michael Jurka0142d492010-08-25 17:46:15 -0700172 // If true, syncPages and syncPageItems will be called to refresh pages
173 protected boolean mContentIsRefreshable = true;
174
175 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700176 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700177
178 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
179 // to switch to a new page
180 protected boolean mUsePagingTouchSlop = true;
181
Michael Jurka8b805b12012-04-18 14:23:14 -0700182 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700183 // (SmoothPagedView does this)
184 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700185 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700186
Patrick Dubroy1262e362010-10-06 15:49:50 -0700187 protected boolean mIsPageMoving = false;
188
Winson Chungf0ea4d32011-06-06 14:27:16 -0700189 // All syncs and layout passes are deferred until data is ready.
190 protected boolean mIsDataReady = false;
191
Adam Cohen7d30a372013-07-01 17:03:59 -0700192 protected boolean mAllowLongPress = true;
193
Winson Chungd2be3812013-07-16 11:11:32 -0700194 // Page Indicator
195 private int mPageIndicatorViewId;
196 private PageIndicator mPageIndicator;
Winson Chung007c6982011-06-14 13:27:53 -0700197
Adam Cohen7d30a372013-07-01 17:03:59 -0700198 // The viewport whether the pages are to be contained (the actual view may be larger than the
199 // viewport)
200 private Rect mViewport = new Rect();
201
202 // Reordering
203 // We use the min scale to determine how much to expand the actually PagedView measured
204 // dimensions such that when we are zoomed out, the view is not clipped
205 private int REORDERING_DROP_REPOSITION_DURATION = 200;
206 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
207 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
208 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 300;
209 private float REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE = 0.1f;
210 private long REORDERING_DELETE_DROP_TARGET_FADE_DURATION = 150;
211 private float mMinScale = 1f;
212 protected View mDragView;
213 protected AnimatorSet mZoomInOutAnim;
214 private Runnable mSidePageHoverRunnable;
215 private int mSidePageHoverIndex = -1;
216 // This variable's scope is only for the duration of startReordering() and endReordering()
217 private boolean mReorderingStarted = false;
218 // This variable's scope is for the duration of startReordering() and after the zoomIn()
219 // animation after endReordering()
220 private boolean mIsReordering;
221 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
222 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
223 private int mPostReorderingPreZoomInRemainingAnimationCount;
224 private Runnable mPostReorderingPreZoomInRunnable;
225
226 // Edge swiping
227 private boolean mOnlyAllowEdgeSwipes = false;
228 private boolean mDownEventOnEdge = false;
229 private int mEdgeSwipeRegionSize = 0;
230
231 // Convenience/caching
232 private Matrix mTmpInvMatrix = new Matrix();
233 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700234 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700235 private Rect mTmpRect = new Rect();
236 private Rect mAltTmpRect = new Rect();
237
238 // Fling to delete
239 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
240 private float FLING_TO_DELETE_FRICTION = 0.035f;
241 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
242 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
243 protected int mFlingToDeleteThresholdVelocity = -1400;
244 // Drag to delete
245 private boolean mDeferringForDelete = false;
246 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
247 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
248
249 // Drop to delete
250 private View mDeleteDropTarget;
251
252 private boolean mAutoComputePageSpacing = false;
253 private boolean mRecomputePageSpacing = false;
254
255 // Bouncer
256 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700257
Winson Chung86f77532010-08-24 11:08:22 -0700258 public interface PageSwitchListener {
259 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700260 }
261
Winson Chung321e9ee2010-08-09 13:37:56 -0700262 public PagedView(Context context) {
263 this(context, null);
264 }
265
266 public PagedView(Context context, AttributeSet attrs) {
267 this(context, attrs, 0);
268 }
269
270 public PagedView(Context context, AttributeSet attrs, int defStyle) {
271 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700272
Adam Cohen9c4949e2010-10-05 12:27:22 -0700273 TypedArray a = context.obtainStyledAttributes(attrs,
274 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800275 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700276 if (mPageSpacing < 0) {
277 mAutoComputePageSpacing = mRecomputePageSpacing = true;
278 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700279 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800280 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700281 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800282 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700283 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800284 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700285 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800286 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700287 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700288 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700289 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700290 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700291 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700292 a.recycle();
293
Winson Chung321e9ee2010-08-09 13:37:56 -0700294 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700295 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700296 }
297
298 /**
299 * Initializes various states for this workspace.
300 */
Michael Jurka0142d492010-08-25 17:46:15 -0700301 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700302 mDirtyPageContent = new ArrayList<Boolean>();
303 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800304 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700305 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700306 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700307
308 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700309 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700310 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
311 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700312 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800313
Adam Cohen7d30a372013-07-01 17:03:59 -0700314 // Scale the fling-to-delete threshold by the density
315 mFlingToDeleteThresholdVelocity =
316 (int) (mFlingToDeleteThresholdVelocity * mDensity);
317
Adam Cohen265b9a62011-12-07 14:37:18 -0800318 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
319 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
320 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700321 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700322 }
323
Winson Chungd2be3812013-07-16 11:11:32 -0700324 protected void onAttachedToWindow() {
325 // Hook up the page indicator
326 ViewGroup parent = (ViewGroup) getParent();
327 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
328 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
329 mPageIndicator.removeAllMarkers();
330 mPageIndicator.addMarkers(getChildCount());
331 }
332 }
333
334 protected void onDetachedFromWindow() {
335 // Unhook the page indicator
336 mPageIndicator = null;
337 }
338
Adam Cohen7d30a372013-07-01 17:03:59 -0700339 void setDeleteDropTarget(View v) {
340 mDeleteDropTarget = v;
341 }
342
343 // Convenience methods to map points from self to parent and vice versa
344 float[] mapPointFromViewToParent(View v, float x, float y) {
345 mTmpPoint[0] = x;
346 mTmpPoint[1] = y;
347 v.getMatrix().mapPoints(mTmpPoint);
348 mTmpPoint[0] += v.getLeft();
349 mTmpPoint[1] += v.getTop();
350 return mTmpPoint;
351 }
352 float[] mapPointFromParentToView(View v, float x, float y) {
353 mTmpPoint[0] = x - v.getLeft();
354 mTmpPoint[1] = y - v.getTop();
355 v.getMatrix().invert(mTmpInvMatrix);
356 mTmpInvMatrix.mapPoints(mTmpPoint);
357 return mTmpPoint;
358 }
359
360 void updateDragViewTranslationDuringDrag() {
361 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
362 float y = mLastMotionY - mDownMotionY;
363 mDragView.setTranslationX(x);
364 mDragView.setTranslationY(y);
365
366 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
367 }
368
369 public void setMinScale(float f) {
370 mMinScale = f;
371 requestLayout();
372 }
373
374 @Override
375 public void setScaleX(float scaleX) {
376 super.setScaleX(scaleX);
377 if (isReordering(true)) {
378 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
379 mLastMotionX = p[0];
380 mLastMotionY = p[1];
381 updateDragViewTranslationDuringDrag();
382 }
383 }
384
385 // Convenience methods to get the actual width/height of the PagedView (since it is measured
386 // to be larger to account for the minimum possible scale)
387 int getViewportWidth() {
388 return mViewport.width();
389 }
390 int getViewportHeight() {
391 return mViewport.height();
392 }
393
394 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
395 // PagedView both horizontally and vertically
396 int getViewportOffsetX() {
397 return (getMeasuredWidth() - getViewportWidth()) / 2;
398 }
399
400 int getViewportOffsetY() {
401 return (getMeasuredHeight() - getViewportHeight()) / 2;
402 }
403
Adam Cohenedb40762013-07-18 16:45:45 -0700404 PageIndicator getPageIndicator() {
405 return mPageIndicator;
406 }
407
Winson Chung86f77532010-08-24 11:08:22 -0700408 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
409 mPageSwitchListener = pageSwitchListener;
410 if (mPageSwitchListener != null) {
411 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700412 }
413 }
414
415 /**
Winson Chung52aee602013-01-30 12:01:02 -0800416 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
417 */
418 public boolean isLayoutRtl() {
419 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
420 }
421
422 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700423 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
424 * out pages.
425 */
426 protected void setDataIsReady() {
427 mIsDataReady = true;
428 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700429
Winson Chungf0ea4d32011-06-06 14:27:16 -0700430 protected boolean isDataReady() {
431 return mIsDataReady;
432 }
433
434 /**
Winson Chung86f77532010-08-24 11:08:22 -0700435 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700436 *
Winson Chung86f77532010-08-24 11:08:22 -0700437 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700438 */
Winson Chung86f77532010-08-24 11:08:22 -0700439 int getCurrentPage() {
440 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700441 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700442
Winson Chung360e63f2012-04-27 13:48:05 -0700443 int getNextPage() {
444 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
445 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700446
Winson Chung86f77532010-08-24 11:08:22 -0700447 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700448 return getChildCount();
449 }
450
Winson Chung86f77532010-08-24 11:08:22 -0700451 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700452 return getChildAt(index);
453 }
454
Adam Cohenae4f1552011-10-20 00:15:42 -0700455 protected int indexToPage(int index) {
456 return index;
457 }
458
Winson Chung321e9ee2010-08-09 13:37:56 -0700459 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800460 * Updates the scroll of the current page immediately to its final scroll position. We use this
461 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
462 * the previous tab page.
463 */
464 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700465 // If the current page is invalid, just reset the scroll position to zero
466 int newX = 0;
467 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700468 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700469 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800470 scrollTo(newX, 0);
471 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800472 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800473 }
474
475 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700476 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
477 * ends, {@link #resumeScrolling()} should be called, along with
478 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
479 */
480 void pauseScrolling() {
481 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700482 }
483
484 /**
485 * Enables scrolling again.
486 * @see #pauseScrolling()
487 */
488 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700489 }
490 /**
Winson Chung86f77532010-08-24 11:08:22 -0700491 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700492 */
Winson Chung86f77532010-08-24 11:08:22 -0700493 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800494 if (!mScroller.isFinished()) {
495 mScroller.abortAnimation();
496 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800497 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
498 // the default
499 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800500 return;
501 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700502
Adam Cohene61a9a22013-06-11 15:45:31 -0700503 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700504 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700505 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700506 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800507 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700508 }
509
Winson Chung8c87cd82013-07-23 16:20:10 -0700510 /**
511 * The restore page will be set in place of the current page at the next (likely first)
512 * layout.
513 */
514 void setRestorePage(int restorePage) {
515 mRestorePage = restorePage;
516 }
517
Michael Jurka0142d492010-08-25 17:46:15 -0700518 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700519 if (mPageSwitchListener != null) {
520 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700521 }
Winson Chungd2be3812013-07-16 11:11:32 -0700522
523 // Update the page indicator (when we aren't reordering)
524 if (mPageIndicator != null && !isReordering(false)) {
525 mPageIndicator.setActiveMarker(getNextPage());
526 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700527 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800528 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700529 if (!mIsPageMoving) {
530 mIsPageMoving = true;
531 onPageBeginMoving();
532 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700533 }
534
Michael Jurkace7e05f2011-02-01 22:02:35 -0800535 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700536 if (mIsPageMoving) {
537 mIsPageMoving = false;
538 onPageEndMoving();
539 }
Michael Jurka0142d492010-08-25 17:46:15 -0700540 }
541
Adam Cohen26976d92011-03-22 15:33:33 -0700542 protected boolean isPageMoving() {
543 return mIsPageMoving;
544 }
545
Michael Jurka0142d492010-08-25 17:46:15 -0700546 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700547 protected void onPageBeginMoving() {
548 }
549
550 // a method that subclasses can override to add behavior
551 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700552 }
553
Winson Chung321e9ee2010-08-09 13:37:56 -0700554 /**
Winson Chung86f77532010-08-24 11:08:22 -0700555 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700556 *
557 * @param l The listener used to respond to long clicks.
558 */
559 @Override
560 public void setOnLongClickListener(OnLongClickListener l) {
561 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700562 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700563 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700564 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700565 }
566 }
567
568 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800569 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700570 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800571 }
572
573 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700574 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700575 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800576 mUnboundedScrollX = x;
577
Adam Cohen0ffac432013-07-10 11:19:26 -0700578 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
579 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
580 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800581 super.scrollTo(0, y);
582 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700583 if (isRtl) {
584 overScroll(x - mMaxScrollX);
585 } else {
586 overScroll(x);
587 }
Adam Cohen68d73932010-11-15 10:50:58 -0800588 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700589 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800590 super.scrollTo(mMaxScrollX, y);
591 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700592 if (isRtl) {
593 overScroll(x);
594 } else {
595 overScroll(x - mMaxScrollX);
596 }
Adam Cohen68d73932010-11-15 10:50:58 -0800597 }
598 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800599 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800600 super.scrollTo(x, y);
601 }
602
Michael Jurka0142d492010-08-25 17:46:15 -0700603 mTouchX = x;
604 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700605
606 // Update the last motion events when scrolling
607 if (isReordering(true)) {
608 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
609 mLastMotionX = p[0];
610 mLastMotionY = p[1];
611 updateDragViewTranslationDuringDrag();
612 }
Michael Jurka0142d492010-08-25 17:46:15 -0700613 }
614
615 // we moved this functionality to a helper function so SmoothPagedView can reuse it
616 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700617 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700618 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700619 if (getScrollX() != mScroller.getCurrX()
620 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700621 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700622 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
623 }
Michael Jurka0142d492010-08-25 17:46:15 -0700624 invalidate();
625 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700626 } else if (mNextPage != INVALID_PAGE) {
627 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700628 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700629 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700630
Winson Chung9c0565f2013-07-19 13:49:06 -0700631 // Load the associated pages if necessary
632 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
633 loadAssociatedPages(mCurrentPage);
634 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
635 }
636
Adam Cohen73aa9752010-11-24 16:26:58 -0800637 // We don't want to trigger a page end moving unless the page has settled
638 // and the user has stopped scrolling
639 if (mTouchState == TOUCH_STATE_REST) {
640 pageEndMoving();
641 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700642
Adam Cohen7d30a372013-07-01 17:03:59 -0700643 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700644 // Notify the user when the page changes
645 AccessibilityManager accessibilityManager = (AccessibilityManager)
646 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
647 if (accessibilityManager.isEnabled()) {
648 AccessibilityEvent ev =
649 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
650 ev.getText().add(getCurrentPageDescription());
651 sendAccessibilityEventUnchecked(ev);
652 }
Michael Jurka0142d492010-08-25 17:46:15 -0700653 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700654 }
Michael Jurka0142d492010-08-25 17:46:15 -0700655 return false;
656 }
657
658 @Override
659 public void computeScroll() {
660 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700661 }
662
Adam Cohen7d30a372013-07-01 17:03:59 -0700663 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
664 return mTopAlignPageWhenShrinkingForBouncer;
665 }
666
Adam Cohen96d30a12013-07-16 18:13:21 -0700667 public static class LayoutParams extends ViewGroup.LayoutParams {
668 public boolean isFullScreenPage = false;
669
670 /**
671 * {@inheritDoc}
672 */
673 public LayoutParams(int width, int height) {
674 super(width, height);
675 }
676
677 public LayoutParams(ViewGroup.LayoutParams source) {
678 super(source);
679 }
680 }
681
682 protected LayoutParams generateDefaultLayoutParams() {
683 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
684 }
685
Adam Cohenedb40762013-07-18 16:45:45 -0700686 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700687 LayoutParams lp = generateDefaultLayoutParams();
688 lp.isFullScreenPage = true;
689 super.addView(page, 0, lp);
690 }
691
Winson Chung321e9ee2010-08-09 13:37:56 -0700692 @Override
693 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700694 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700695 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
696 return;
697 }
698
Adam Cohen7d30a372013-07-01 17:03:59 -0700699 // We measure the dimensions of the PagedView to be larger than the pages so that when we
700 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700701 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
702 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
703 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700704 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700705 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
706 // viewport, we can be at most one and a half screens offset once we scale down
707 DisplayMetrics dm = getResources().getDisplayMetrics();
708 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
709 int parentWidthSize = (int) (1.5f * maxSize);
710 int parentHeightSize = maxSize;
711 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
712 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
713 mViewport.set(0, 0, widthSize, heightSize);
714
715 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
716 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
717 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700718 }
719
Winson Chung8aad6102012-05-11 16:27:49 -0700720 // Return early if we aren't given a proper dimension
721 if (widthSize <= 0 || heightSize <= 0) {
722 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
723 return;
724 }
725
Adam Lesinski6b879f02010-11-04 16:15:23 -0700726 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
727 * of the All apps view on XLarge displays to not take up more space then it needs. Width
728 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
729 * each page to have the same width.
730 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700731 final int verticalPadding = getPaddingTop() + getPaddingBottom();
732 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700733
734 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700735 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700736 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700737 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
738 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
739 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
740 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700741 final int childCount = getChildCount();
742 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700743 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700744 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700745 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
746
747 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700748 int childHeightMode;
749 int childWidth;
750 int childHeight;
751
752 if (!lp.isFullScreenPage) {
753 if (lp.width == LayoutParams.WRAP_CONTENT) {
754 childWidthMode = MeasureSpec.AT_MOST;
755 } else {
756 childWidthMode = MeasureSpec.EXACTLY;
757 }
758
759 if (lp.height == LayoutParams.WRAP_CONTENT) {
760 childHeightMode = MeasureSpec.AT_MOST;
761 } else {
762 childHeightMode = MeasureSpec.EXACTLY;
763 }
764
765 childWidth = widthSize - horizontalPadding;
766 childHeight = heightSize - verticalPadding;
767
Michael Jurka5f1c5092010-09-03 14:15:02 -0700768 } else {
769 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700770 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700771
772 childWidth = getViewportWidth();
773 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700774 }
775
776 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700777 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
778 final int childHeightMeasureSpec =
779 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700780 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700781 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700782 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700783
Winson Chunga128a7b2012-04-30 15:23:15 -0700784 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700785 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700786 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700787 // The gap between pages in the PagedView should be equal to the gap from the page
788 // to the edge of the screen (so it is not visible in the current screen). To
789 // account for unequal padding on each side of the paged view, we take the maximum
790 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700791 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700792 int spacing = Math.max(offset, widthSize - offset -
793 getChildAt(0).getMeasuredWidth());
794 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700795 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700796 }
797 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700798 }
799
Adam Cohen60b07122011-11-14 17:26:06 -0800800 public void setPageSpacing(int pageSpacing) {
801 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700802 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800803 }
804
Winson Chung321e9ee2010-08-09 13:37:56 -0700805 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700806 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700807 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700808 return;
809 }
810
Winson Chung785d2eb2011-04-14 16:08:02 -0700811 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700812 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700813
Adam Cohenedb40762013-07-18 16:45:45 -0700814 int screenWidth = getViewportWidth();
815
Adam Cohen7d30a372013-07-01 17:03:59 -0700816 int offsetX = getViewportOffsetX();
817 int offsetY = getViewportOffsetY();
818
819 // Update the viewport offsets
820 mViewport.offset(offsetX, offsetY);
821
Adam Cohen0ffac432013-07-10 11:19:26 -0700822 final boolean isRtl = isLayoutRtl();
823
824 final int startIndex = isRtl ? childCount - 1 : 0;
825 final int endIndex = isRtl ? -1 : childCount;
826 final int delta = isRtl ? -1 : 1;
827
Adam Cohen7d30a372013-07-01 17:03:59 -0700828 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700829 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
830
831 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
832 mPageScrolls = new int[getChildCount()];
833 }
834
Adam Cohen0ffac432013-07-10 11:19:26 -0700835 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700836 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700837 LayoutParams lp = (LayoutParams) child.getLayoutParams();
838 int childTop;
839
840 if (lp.isFullScreenPage) {
841 childTop = offsetY;
842 } else {
843 childTop = offsetY + getPaddingTop();
844 if (mCenterPagesVertically) {
845 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
846 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700847 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700848
Winson Chung321e9ee2010-08-09 13:37:56 -0700849 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700850 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700851 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800852
Winson Chung785d2eb2011-04-14 16:08:02 -0700853 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700854 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800855 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700856
857 // We assume the left and right padding are equal, and hence center the pages
858 // horizontally
859 int scrollOffset = false ? 0 : (getViewportWidth() - childWidth) / 2;
860 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
861
Adam Cohen9c4949e2010-10-05 12:27:22 -0700862 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700863 }
864 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700865
866 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
867 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800868 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700869 setHorizontalScrollBarEnabled(true);
870 mFirstLayout = false;
871 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700872
873 if (childCount > 0) {
874 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700875 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700876 } else {
877 mMaxScrollX = 0;
878 }
879
880 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
881 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700882 if (mRestorePage > -1) {
883 setCurrentPage(mRestorePage);
884 mRestorePage = -1;
885 } else {
886 setCurrentPage(getNextPage());
887 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700888 }
889 mChildCountOnLastLayout = getChildCount();
Winson Chunge3193b92010-09-10 11:44:42 -0700890 }
891
Adam Cohenf34bab52010-09-30 14:11:56 -0700892 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700893 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
894
895 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700896 for (int i = 0; i < getChildCount(); i++) {
897 View child = getChildAt(i);
898 if (child != null) {
899 float scrollProgress = getScrollProgress(screenCenter, child, i);
900 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800901 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700902 }
903 }
904 invalidate();
905 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700906 }
907
Winson Chunge3193b92010-09-10 11:44:42 -0700908 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700909 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700910 // 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.addMarker(indexOfChild(child));
914 }
915
Adam Cohen2591f6a2011-10-25 14:36:40 -0700916 // This ensures that when children are added, they get the correct transforms / alphas
917 // in accordance with any scroll effects.
918 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700919 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700920
Adam Cohen2591f6a2011-10-25 14:36:40 -0700921 invalidate();
922 }
923
Michael Jurka8b805b12012-04-18 14:23:14 -0700924 @Override
925 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700926 mForceScreenScrolled = true;
927 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700928 }
929
Winson Chungd2be3812013-07-16 11:11:32 -0700930 private void removeMarkerForView(int index) {
931 // Update the page indicator, we don't update the page indicator as we
932 // add/remove pages
933 if (mPageIndicator != null && !isReordering(false)) {
934 mPageIndicator.removeMarker(index);
935 }
936 }
937
938 @Override
939 public void removeView(View v) {
940 // XXX: We should find a better way to hook into this before the view
941 // gets removed form its parent...
942 removeMarkerForView(indexOfChild(v));
943 super.removeView(v);
944 }
945 @Override
946 public void removeViewInLayout(View v) {
947 // XXX: We should find a better way to hook into this before the view
948 // gets removed form its parent...
949 removeMarkerForView(indexOfChild(v));
950 super.removeViewInLayout(v);
951 }
952 @Override
953 public void removeViewAt(int index) {
954 // XXX: We should find a better way to hook into this before the view
955 // gets removed form its parent...
956 removeViewAt(index);
957 super.removeViewAt(index);
958 }
959 @Override
960 public void removeAllViewsInLayout() {
961 // Update the page indicator, we don't update the page indicator as we
962 // add/remove pages
963 if (mPageIndicator != null) {
964 mPageIndicator.removeAllMarkers();
965 }
966
967 super.removeAllViewsInLayout();
968 }
969
Adam Cohen73894962011-10-31 13:17:17 -0700970 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700971 if (index < 0 || index > getChildCount() - 1) return 0;
972
Adam Cohen0ffac432013-07-10 11:19:26 -0700973 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700974
Adam Cohenf698c6e2013-07-17 18:44:25 -0700975 if (isRtl) index = getChildCount() - index - 1;
976 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -0700977
Adam Cohenf698c6e2013-07-17 18:44:25 -0700978 return offset;
Adam Cohen73894962011-10-31 13:17:17 -0700979 }
980
Winson Chungc9ca2982013-07-19 12:07:38 -0700981 void getReorderablePages(int[] range) {
982 range[0] = 0;
983 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -0700984 }
985
Michael Jurkadde558b2011-11-09 22:09:06 -0800986 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -0700987 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -0700988 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -0700989
Michael Jurkac4fb9172010-09-02 17:19:20 -0700990 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -0700991 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -0700992 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -0700993 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -0700994
Winson Chungc9ca2982013-07-19 12:07:38 -0700995 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
996 View currPage = getPageAt(leftScreen);
997
998 // Check if the right edge of the page is in the viewport
999 mTmpIntPoint[0] = currPage.getMeasuredWidth();
1000 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1001 if (mTmpIntPoint[0] < 0) {
1002 break;
1003 }
1004 }
1005 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1006 View currPage = getPageAt(rightScreen);
1007
1008 // Check if the left edge of the page is in the viewport
1009 mTmpIntPoint[0] = 0;
1010 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1011 if (mTmpIntPoint[0] >= viewportWidth) {
1012 break;
1013 }
1014 }
1015 range[0] = Math.max(0, leftScreen);
1016 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001017 } else {
1018 range[0] = -1;
1019 range[1] = -1;
1020 }
1021 }
1022
Michael Jurka920d7f42012-05-14 16:29:55 -07001023 protected boolean shouldDrawChild(View child) {
1024 return child.getAlpha() > 0;
1025 }
1026
Michael Jurkadde558b2011-11-09 22:09:06 -08001027 @Override
1028 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001029 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001030 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1031 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001032 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001033
1034 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001035 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1036 // set it for the next frame
1037 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001038 screenScrolled(screenCenter);
1039 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001040 }
1041
1042 // Find out which screens are visible; as an optimization we only call draw on them
1043 final int pageCount = getChildCount();
1044 if (pageCount > 0) {
1045 getVisiblePages(mTempVisiblePagesRange);
1046 final int leftScreen = mTempVisiblePagesRange[0];
1047 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001048 if (leftScreen != -1 && rightScreen != -1) {
1049 final long drawingTime = getDrawingTime();
1050 // Clip to the bounds
1051 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001052 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1053 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001054
Adam Cohen7d30a372013-07-01 17:03:59 -07001055 // Draw all the children, leaving the drag view for last
1056 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001057 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001058 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001059 if (mForceDrawAllChildrenNextFrame ||
1060 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001061 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001062 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001063 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001064 // Draw the drag view on top (if there is one)
1065 if (mDragView != null) {
1066 drawChild(canvas, mDragView, drawingTime);
1067 }
1068
Michael Jurka5e368ff2012-05-14 23:13:15 -07001069 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001070 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001071 }
Michael Jurka0142d492010-08-25 17:46:15 -07001072 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001073 }
1074
1075 @Override
1076 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001077 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001078 if (page != mCurrentPage || !mScroller.isFinished()) {
1079 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001080 return true;
1081 }
1082 return false;
1083 }
1084
1085 @Override
1086 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001087 int focusablePage;
1088 if (mNextPage != INVALID_PAGE) {
1089 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001090 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001091 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001092 }
Winson Chung86f77532010-08-24 11:08:22 -07001093 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001094 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001095 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001096 }
1097 return false;
1098 }
1099
1100 @Override
1101 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001102 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001103 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001104 if (getCurrentPage() > 0) {
1105 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001106 return true;
1107 }
1108 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001109 if (getCurrentPage() < getPageCount() - 1) {
1110 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001111 return true;
1112 }
1113 }
1114 return super.dispatchUnhandledMove(focused, direction);
1115 }
1116
1117 @Override
1118 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001119 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001120 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001121 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001122 }
1123 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001124 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001125 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001126 }
1127 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001128 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001129 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001130 }
1131 }
1132 }
1133
1134 /**
1135 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001136 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001137 *
Winson Chung86f77532010-08-24 11:08:22 -07001138 * This happens when live folders requery, and if they're off page, they
1139 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001140 */
1141 @Override
1142 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001143 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001144 View v = focused;
1145 while (true) {
1146 if (v == current) {
1147 super.focusableViewAvailable(focused);
1148 return;
1149 }
1150 if (v == this) {
1151 return;
1152 }
1153 ViewParent parent = v.getParent();
1154 if (parent instanceof View) {
1155 v = (View)v.getParent();
1156 } else {
1157 return;
1158 }
1159 }
1160 }
1161
1162 /**
1163 * {@inheritDoc}
1164 */
1165 @Override
1166 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1167 if (disallowIntercept) {
1168 // We need to make sure to cancel our long press if
1169 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001170 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001171 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001172 }
1173 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1174 }
1175
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001176 /**
1177 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1178 */
1179 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001180 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001181 if (isLayoutRtl()) {
1182 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001183 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001184 }
Adam Cohenedb40762013-07-18 16:45:45 -07001185 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001186 }
1187
1188 /**
1189 * Return true if a tap at (x, y) should trigger a flip to the next page.
1190 */
1191 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001192 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001193 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001194 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001195 }
1196 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001197 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001198 }
Winson Chung52aee602013-01-30 12:01:02 -08001199
Adam Cohen7d30a372013-07-01 17:03:59 -07001200 /** Returns whether x and y originated within the buffered viewport */
1201 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1202 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1203 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1204 return mTmpRect.contains(x, y);
1205 }
1206
1207 /** Returns whether x and y originated within the current page view bounds */
1208 private boolean isTouchPointInCurrentPage(int x, int y) {
1209 View v = getPageAt(getCurrentPage());
1210 if (v != null) {
1211 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1212 v.getBottom());
1213 return mTmpRect.contains(x, y);
1214 }
1215 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001216 }
1217
Winson Chung321e9ee2010-08-09 13:37:56 -07001218 @Override
1219 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001220 if (DISABLE_TOUCH_INTERACTION) {
1221 return false;
1222 }
1223
Winson Chung321e9ee2010-08-09 13:37:56 -07001224 /*
1225 * This method JUST determines whether we want to intercept the motion.
1226 * If we return true, onTouchEvent will be called and we do the actual
1227 * scrolling there.
1228 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001229 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001230
Winson Chung45e1d6e2010-11-09 17:19:49 -08001231 // Skip touch handling if there are no pages to swipe
1232 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1233
Winson Chung321e9ee2010-08-09 13:37:56 -07001234 /*
1235 * Shortcut the most recurring case: the user is in the dragging
1236 * state and he is moving his finger. We want to intercept this
1237 * motion.
1238 */
1239 final int action = ev.getAction();
1240 if ((action == MotionEvent.ACTION_MOVE) &&
1241 (mTouchState == TOUCH_STATE_SCROLLING)) {
1242 return true;
1243 }
1244
Winson Chung321e9ee2010-08-09 13:37:56 -07001245 switch (action & MotionEvent.ACTION_MASK) {
1246 case MotionEvent.ACTION_MOVE: {
1247 /*
1248 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1249 * whether the user has moved far enough from his original down touch.
1250 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001251 if (mActivePointerId != INVALID_POINTER) {
1252 determineScrollingStart(ev);
1253 break;
1254 }
1255 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1256 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1257 // i.e. fall through to the next case (don't break)
1258 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1259 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001260 }
1261
1262 case MotionEvent.ACTION_DOWN: {
1263 final float x = ev.getX();
1264 final float y = ev.getY();
1265 // Remember location of down touch
1266 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001267 mDownMotionY = y;
1268 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001269 mLastMotionX = x;
1270 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001271 float[] p = mapPointFromViewToParent(this, x, y);
1272 mParentDownMotionX = p[0];
1273 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001274 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001275 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001276 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001277
1278 // Determine if the down event is within the threshold to be an edge swipe
1279 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1280 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1281 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1282 mDownEventOnEdge = true;
1283 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001284
1285 /*
1286 * If being flinged and user touches the screen, initiate drag;
1287 * otherwise don't. mScroller.isFinished should be false when
1288 * being flinged.
1289 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001290 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001291 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1292 if (finishedScrolling) {
1293 mTouchState = TOUCH_STATE_REST;
1294 mScroller.abortAnimation();
1295 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001296 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1297 mTouchState = TOUCH_STATE_SCROLLING;
1298 } else {
1299 mTouchState = TOUCH_STATE_REST;
1300 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001301 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001302
Winson Chung86f77532010-08-24 11:08:22 -07001303 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001304 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001305 if (!DISABLE_TOUCH_SIDE_PAGES) {
1306 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1307 if (getChildCount() > 0) {
1308 if (hitsPreviousPage(x, y)) {
1309 mTouchState = TOUCH_STATE_PREV_PAGE;
1310 } else if (hitsNextPage(x, y)) {
1311 mTouchState = TOUCH_STATE_NEXT_PAGE;
1312 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001313 }
1314 }
1315 }
1316 break;
1317 }
1318
Winson Chung321e9ee2010-08-09 13:37:56 -07001319 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001320 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001321 resetTouchState();
1322 // Just intercept the touch event on up if we tap outside the strict viewport
1323 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1324 return true;
1325 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001326 break;
1327
1328 case MotionEvent.ACTION_POINTER_UP:
1329 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001330 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001331 break;
1332 }
1333
1334 /*
1335 * The only time we want to intercept motion events is if we are in the
1336 * drag mode.
1337 */
1338 return mTouchState != TOUCH_STATE_REST;
1339 }
1340
Adam Cohenf8d28232011-02-01 21:47:00 -08001341 protected void determineScrollingStart(MotionEvent ev) {
1342 determineScrollingStart(ev, 1.0f);
1343 }
1344
Winson Chung321e9ee2010-08-09 13:37:56 -07001345 /*
1346 * Determines if we should change the touch state to start scrolling after the
1347 * user moves their touch point too far.
1348 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001349 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001350 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001351 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001352 if (pointerIndex == -1) return;
1353
1354 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001355 final float x = ev.getX(pointerIndex);
1356 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001357 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1358
1359 // If we're only allowing edge swipes, we break out early if the down event wasn't
1360 // at the edge.
1361 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1362
Winson Chung321e9ee2010-08-09 13:37:56 -07001363 final int xDiff = (int) Math.abs(x - mLastMotionX);
1364 final int yDiff = (int) Math.abs(y - mLastMotionY);
1365
Adam Cohenf8d28232011-02-01 21:47:00 -08001366 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001367 boolean xPaged = xDiff > mPagingTouchSlop;
1368 boolean xMoved = xDiff > touchSlop;
1369 boolean yMoved = yDiff > touchSlop;
1370
Adam Cohenf8d28232011-02-01 21:47:00 -08001371 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001372 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001373 // Scroll if the user moved far enough along the X axis
1374 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001375 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001376 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001377 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001378 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001379 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1380 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001381 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001382 }
1383 }
1384
Adam Cohen7d30a372013-07-01 17:03:59 -07001385 protected float getMaxScrollProgress() {
1386 return 1.0f;
1387 }
1388
Adam Cohenf8d28232011-02-01 21:47:00 -08001389 protected void cancelCurrentPageLongPress() {
1390 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001391 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001392 // Try canceling the long press. It could also have been scheduled
1393 // by a distant descendant, so use the mAllowLongPress flag to block
1394 // everything
1395 final View currentPage = getPageAt(mCurrentPage);
1396 if (currentPage != null) {
1397 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001398 }
1399 }
1400 }
1401
Adam Cohen7d30a372013-07-01 17:03:59 -07001402 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1403 final int halfScreenSize = getViewportWidth() / 2;
1404
1405 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1406 screenCenter = Math.max(halfScreenSize, screenCenter);
1407
1408 return getScrollProgress(screenCenter, v, page);
1409 }
1410
Adam Cohenb5ba0972011-09-07 18:02:31 -07001411 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001412 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001413
Adam Cohen96d30a12013-07-16 18:13:21 -07001414 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001415 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001416
1417 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001418 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1419 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001420 return scrollProgress;
1421 }
1422
Adam Cohenedb40762013-07-18 16:45:45 -07001423 public int getScrollForPage(int index) {
1424 if (mPageScrolls == null || index >= mPageScrolls.length) {
1425 return 0;
1426 } else {
1427 return mPageScrolls[index];
1428 }
1429 }
1430
Adam Cohene0f66b52010-11-23 15:06:07 -08001431 // This curve determines how the effect of scrolling over the limits of the page dimishes
1432 // as the user pulls further and further from the bounds
1433 private float overScrollInfluenceCurve(float f) {
1434 f -= 1.0f;
1435 return f * f * f + 1.0f;
1436 }
1437
Adam Cohenb5ba0972011-09-07 18:02:31 -07001438 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001439 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001440
1441 // We want to reach the max over scroll effect when the user has
1442 // over scrolled half the size of the screen
1443 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1444
1445 if (f == 0) return;
1446
1447 // Clamp this factor, f, to -1 < f < 1
1448 if (Math.abs(f) >= 1) {
1449 f /= Math.abs(f);
1450 }
1451
1452 int overScrollAmount = (int) Math.round(f * screenSize);
1453 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001454 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001455 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001456 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001457 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001458 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001459 }
1460 invalidate();
1461 }
1462
1463 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001464 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001465
1466 float f = (amount / screenSize);
1467
1468 if (f == 0) return;
1469 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1470
Adam Cohen7bfc9792011-01-28 13:52:37 -08001471 // Clamp this factor, f, to -1 < f < 1
1472 if (Math.abs(f) >= 1) {
1473 f /= Math.abs(f);
1474 }
1475
Adam Cohene0f66b52010-11-23 15:06:07 -08001476 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001477 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001478 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001479 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001480 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001481 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001482 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001483 }
1484 invalidate();
1485 }
1486
Adam Cohenb5ba0972011-09-07 18:02:31 -07001487 protected void overScroll(float amount) {
1488 dampedOverScroll(amount);
1489 }
1490
Michael Jurkac5b262c2011-01-12 20:24:50 -08001491 protected float maxOverScroll() {
1492 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001493 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001494 float f = 1.0f;
1495 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1496 return OVERSCROLL_DAMP_FACTOR * f;
1497 }
1498
Winson Chung321e9ee2010-08-09 13:37:56 -07001499 @Override
1500 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001501 if (DISABLE_TOUCH_INTERACTION) {
1502 return false;
1503 }
1504
Winson Chung45e1d6e2010-11-09 17:19:49 -08001505 // Skip touch handling if there are no pages to swipe
1506 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1507
Michael Jurkab8f06722010-10-10 15:58:46 -07001508 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001509
1510 final int action = ev.getAction();
1511
1512 switch (action & MotionEvent.ACTION_MASK) {
1513 case MotionEvent.ACTION_DOWN:
1514 /*
1515 * If being flinged and user touches, stop the fling. isFinished
1516 * will be false if being flinged.
1517 */
1518 if (!mScroller.isFinished()) {
1519 mScroller.abortAnimation();
1520 }
1521
1522 // Remember where the motion event started
1523 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001524 mDownMotionY = mLastMotionY = ev.getY();
1525 mDownScrollX = getScrollX();
1526 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1527 mParentDownMotionX = p[0];
1528 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001529 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001530 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001531 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001532
1533 // Determine if the down event is within the threshold to be an edge swipe
1534 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1535 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1536 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1537 mDownEventOnEdge = true;
1538 }
1539
Michael Jurka0142d492010-08-25 17:46:15 -07001540 if (mTouchState == TOUCH_STATE_SCROLLING) {
1541 pageBeginMoving();
1542 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001543 break;
1544
1545 case MotionEvent.ACTION_MOVE:
1546 if (mTouchState == TOUCH_STATE_SCROLLING) {
1547 // Scroll to follow the motion event
1548 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001549
1550 if (pointerIndex == -1) return true;
1551
Winson Chung321e9ee2010-08-09 13:37:56 -07001552 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001553 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001554
Adam Cohenaefd4e12011-02-14 16:39:38 -08001555 mTotalMotionX += Math.abs(deltaX);
1556
Winson Chungc0844aa2011-02-02 15:25:58 -08001557 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1558 // keep the remainder because we are actually testing if we've moved from the last
1559 // scrolled position (which is discrete).
1560 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001561 mTouchX += deltaX;
1562 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1563 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001564 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001565 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001566 } else {
1567 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001568 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001569 mLastMotionX = x;
1570 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001571 } else {
1572 awakenScrollBars();
1573 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001574 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1575 // Update the last motion position
1576 mLastMotionX = ev.getX();
1577 mLastMotionY = ev.getY();
1578
1579 // Update the parent down so that our zoom animations take this new movement into
1580 // account
1581 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1582 mParentDownMotionX = pt[0];
1583 mParentDownMotionY = pt[1];
1584 updateDragViewTranslationDuringDrag();
1585
1586 // Find the closest page to the touch point
1587 final int dragViewIndex = indexOfChild(mDragView);
1588 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1589 getViewportWidth());
1590 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1591 + bufferSize);
1592 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1593 - bufferSize);
1594
1595 // Change the drag view if we are hovering over the drop target
1596 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1597 (int) mParentDownMotionX, (int) mParentDownMotionY);
1598 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1599
1600 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1601 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1602 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1603 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1604 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1605 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1606
1607 float parentX = mParentDownMotionX;
1608 int pageIndexToSnapTo = -1;
1609 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1610 pageIndexToSnapTo = dragViewIndex - 1;
1611 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1612 pageIndexToSnapTo = dragViewIndex + 1;
1613 }
1614
1615 final int pageUnderPointIndex = pageIndexToSnapTo;
1616 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1617 mTempVisiblePagesRange[0] = 0;
1618 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07001619 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001620 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1621 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1622 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1623 mSidePageHoverIndex = pageUnderPointIndex;
1624 mSidePageHoverRunnable = new Runnable() {
1625 @Override
1626 public void run() {
1627 // Update the down scroll position to account for the fact that the
1628 // current page is moved
Adam Cohenedb40762013-07-18 16:45:45 -07001629 mDownScrollX = getScrollForPage(pageUnderPointIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001630
1631 // Setup the scroll to the correct page before we swap the views
1632 snapToPage(pageUnderPointIndex);
1633
1634 // For each of the pages between the paged view and the drag view,
1635 // animate them from the previous position to the new position in
1636 // the layout (as a result of the drag view moving in the layout)
1637 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1638 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1639 dragViewIndex + 1 : pageUnderPointIndex;
1640 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1641 dragViewIndex - 1 : pageUnderPointIndex;
1642 for (int i = lowerIndex; i <= upperIndex; ++i) {
1643 View v = getChildAt(i);
1644 // dragViewIndex < pageUnderPointIndex, so after we remove the
1645 // drag view all subsequent views to pageUnderPointIndex will
1646 // shift down.
1647 int oldX = getViewportOffsetX() + getChildOffset(i);
1648 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1649
1650 // Animate the view translation from its old position to its new
1651 // position
1652 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1653 if (anim != null) {
1654 anim.cancel();
1655 }
1656
1657 v.setTranslationX(oldX - newX);
1658 anim = new AnimatorSet();
1659 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1660 anim.playTogether(
1661 ObjectAnimator.ofFloat(v, "translationX", 0f));
1662 anim.start();
1663 v.setTag(anim);
1664 }
1665
1666 removeView(mDragView);
1667 onRemoveView(mDragView, false);
1668 addView(mDragView, pageUnderPointIndex);
1669 onAddView(mDragView, pageUnderPointIndex);
1670 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001671 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001672 }
1673 };
1674 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1675 }
1676 } else {
1677 removeCallbacks(mSidePageHoverRunnable);
1678 mSidePageHoverIndex = -1;
1679 }
Adam Cohen564976a2010-10-13 18:52:07 -07001680 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001681 determineScrollingStart(ev);
1682 }
1683 break;
1684
1685 case MotionEvent.ACTION_UP:
1686 if (mTouchState == TOUCH_STATE_SCROLLING) {
1687 final int activePointerId = mActivePointerId;
1688 final int pointerIndex = ev.findPointerIndex(activePointerId);
1689 final float x = ev.getX(pointerIndex);
1690 final VelocityTracker velocityTracker = mVelocityTracker;
1691 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1692 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001693 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001694 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001695 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1696 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001697
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001698 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1699
Adam Cohen00481b32011-11-18 12:03:48 -08001700 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001701 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001702
Adam Cohenaefd4e12011-02-14 16:39:38 -08001703 // In the case that the page is moved far to one direction and then is flung
1704 // in the opposite direction, we use a threshold to determine whether we should
1705 // just return to the starting page, or if we should skip one further.
1706 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001707 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001708 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001709 returnToOriginalPage = true;
1710 }
1711
Adam Cohenaefd4e12011-02-14 16:39:38 -08001712 int finalPage;
1713 // We give flings precedence over large moves, which is why we short-circuit our
1714 // test for a large move if a fling has been registered. That is, a large
1715 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001716 final boolean isRtl = isLayoutRtl();
1717 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1718 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1719 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1720 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001721 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1722 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001723 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1724 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001725 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001726 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1727 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001728 } else {
1729 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001730 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001731 // at this point we have not moved beyond the touch slop
1732 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1733 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001734 int nextPage = Math.max(0, mCurrentPage - 1);
1735 if (nextPage != mCurrentPage) {
1736 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001737 } else {
1738 snapToDestination();
1739 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001740 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001741 // at this point we have not moved beyond the touch slop
1742 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1743 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001744 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1745 if (nextPage != mCurrentPage) {
1746 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001747 } else {
1748 snapToDestination();
1749 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001750 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1751 // Update the last motion position
1752 mLastMotionX = ev.getX();
1753 mLastMotionY = ev.getY();
1754
1755 // Update the parent down so that our zoom animations take this new movement into
1756 // account
1757 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1758 mParentDownMotionX = pt[0];
1759 mParentDownMotionY = pt[1];
1760 updateDragViewTranslationDuringDrag();
1761 boolean handledFling = false;
1762 if (!DISABLE_FLING_TO_DELETE) {
1763 // Check the velocity and see if we are flinging-to-delete
1764 PointF flingToDeleteVector = isFlingingToDelete();
1765 if (flingToDeleteVector != null) {
1766 onFlingToDelete(flingToDeleteVector);
1767 handledFling = true;
1768 }
1769 }
1770 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1771 (int) mParentDownMotionY)) {
1772 onDropToDelete();
1773 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001774 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001775 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001776 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001777
1778 // Remove the callback to wait for the side page hover timeout
1779 removeCallbacks(mSidePageHoverRunnable);
1780 // End any intermediate reordering states
1781 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001782 break;
1783
1784 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001785 if (mTouchState == TOUCH_STATE_SCROLLING) {
1786 snapToDestination();
1787 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001788 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001789 break;
1790
1791 case MotionEvent.ACTION_POINTER_UP:
1792 onSecondaryPointerUp(ev);
1793 break;
1794 }
1795
1796 return true;
1797 }
1798
Adam Cohen7d30a372013-07-01 17:03:59 -07001799 public void onFlingToDelete(View v) {}
1800 public void onRemoveView(View v, boolean deletePermanently) {}
1801 public void onRemoveViewAnimationCompleted() {}
1802 public void onAddView(View v, int index) {}
1803
1804 private void resetTouchState() {
1805 releaseVelocityTracker();
1806 endReordering();
1807 mTouchState = TOUCH_STATE_REST;
1808 mActivePointerId = INVALID_POINTER;
1809 mDownEventOnEdge = false;
1810 }
1811
1812 protected void onUnhandledTap(MotionEvent ev) {}
1813
Winson Chung185d7162011-02-28 13:47:29 -08001814 @Override
1815 public boolean onGenericMotionEvent(MotionEvent event) {
1816 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1817 switch (event.getAction()) {
1818 case MotionEvent.ACTION_SCROLL: {
1819 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1820 final float vscroll;
1821 final float hscroll;
1822 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1823 vscroll = 0;
1824 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1825 } else {
1826 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1827 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1828 }
1829 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001830 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1831 : (hscroll > 0 || vscroll > 0);
1832 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001833 scrollRight();
1834 } else {
1835 scrollLeft();
1836 }
1837 return true;
1838 }
1839 }
1840 }
1841 }
1842 return super.onGenericMotionEvent(event);
1843 }
1844
Michael Jurkab8f06722010-10-10 15:58:46 -07001845 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1846 if (mVelocityTracker == null) {
1847 mVelocityTracker = VelocityTracker.obtain();
1848 }
1849 mVelocityTracker.addMovement(ev);
1850 }
1851
1852 private void releaseVelocityTracker() {
1853 if (mVelocityTracker != null) {
1854 mVelocityTracker.recycle();
1855 mVelocityTracker = null;
1856 }
1857 }
1858
Winson Chung321e9ee2010-08-09 13:37:56 -07001859 private void onSecondaryPointerUp(MotionEvent ev) {
1860 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1861 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1862 final int pointerId = ev.getPointerId(pointerIndex);
1863 if (pointerId == mActivePointerId) {
1864 // This was our active pointer going up. Choose a new
1865 // active pointer and adjust accordingly.
1866 // TODO: Make this decision more intelligent.
1867 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1868 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1869 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001870 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001871 mActivePointerId = ev.getPointerId(newPointerIndex);
1872 if (mVelocityTracker != null) {
1873 mVelocityTracker.clear();
1874 }
1875 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001876 }
1877
Winson Chung321e9ee2010-08-09 13:37:56 -07001878 @Override
1879 public void requestChildFocus(View child, View focused) {
1880 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001881 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001882 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001883 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001884 }
1885 }
1886
Winson Chung1908d072011-02-24 18:09:44 -08001887 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001888 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001889 }
1890
Adam Cohen7d30a372013-07-01 17:03:59 -07001891 int getPageNearestToPoint(float x) {
1892 int index = 0;
1893 for (int i = 0; i < getChildCount(); ++i) {
1894 if (x < getChildAt(i).getRight() - getScrollX()) {
1895 return index;
1896 } else {
1897 index++;
1898 }
1899 }
1900 return Math.min(index, getChildCount() - 1);
1901 }
1902
Adam Cohend19d3ca2010-09-15 14:43:42 -07001903 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001904 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001905 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001906 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001907 final int childCount = getChildCount();
1908 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001909 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001910 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001911 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001912 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001913 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1914 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1915 minDistanceFromScreenCenter = distanceFromScreenCenter;
1916 minDistanceFromScreenCenterIndex = i;
1917 }
1918 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001919 return minDistanceFromScreenCenterIndex;
1920 }
1921
1922 protected void snapToDestination() {
1923 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001924 }
1925
Adam Cohene0f66b52010-11-23 15:06:07 -08001926 private static class ScrollInterpolator implements Interpolator {
1927 public ScrollInterpolator() {
1928 }
1929
1930 public float getInterpolation(float t) {
1931 t -= 1.0f;
1932 return t*t*t*t*t + 1;
1933 }
1934 }
1935
1936 // We want the duration of the page snap animation to be influenced by the distance that
1937 // the screen has to travel, however, we don't want this duration to be effected in a
1938 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1939 // of travel has on the overall snap duration.
1940 float distanceInfluenceForSnapDuration(float f) {
1941 f -= 0.5f; // center the values about 0.
1942 f *= 0.3f * Math.PI / 2.0f;
1943 return (float) Math.sin(f);
1944 }
1945
Michael Jurka0142d492010-08-25 17:46:15 -07001946 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001947 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001948 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001949
Adam Cohenedb40762013-07-18 16:45:45 -07001950 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08001951 int delta = newX - mUnboundedScrollX;
1952 int duration = 0;
1953
Adam Cohen265b9a62011-12-07 14:37:18 -08001954 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001955 // If the velocity is low enough, then treat this more as an automatic page advance
1956 // as opposed to an apparent physical response to flinging
1957 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1958 return;
1959 }
1960
1961 // Here we compute a "distance" that will be used in the computation of the overall
1962 // snap duration. This is a function of the actual distance that needs to be traveled;
1963 // we keep this value close to half screen size in order to reduce the variance in snap
1964 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001965 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001966 float distance = halfScreenSize + halfScreenSize *
1967 distanceInfluenceForSnapDuration(distanceRatio);
1968
1969 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001970 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001971
1972 // we want the page's snap velocity to approximately match the velocity at which the
1973 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001974 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1975 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001976
1977 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001978 }
1979
1980 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001981 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001982 }
1983
Adam Cohen7d30a372013-07-01 17:03:59 -07001984 protected void snapToPageImmediately(int whichPage) {
1985 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1986 }
1987
Michael Jurka0142d492010-08-25 17:46:15 -07001988 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001989 snapToPage(whichPage, duration, false);
1990 }
1991
1992 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07001993 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07001994
Adam Cohenedb40762013-07-18 16:45:45 -07001995 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08001996 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001997 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07001998 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07001999 }
2000
2001 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002002 snapToPage(whichPage, delta, duration, false);
2003 }
Michael Jurka0142d492010-08-25 17:46:15 -07002004
Adam Cohen7d30a372013-07-01 17:03:59 -07002005 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2006 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002007 View focusedChild = getFocusedChild();
2008 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002009 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002010 focusedChild.clearFocus();
2011 }
2012
2013 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002014 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002015 if (immediate) {
2016 duration = 0;
2017 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002018 duration = Math.abs(delta);
2019 }
2020
2021 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002022 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002023
Michael Jurka0142d492010-08-25 17:46:15 -07002024 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002025
2026 // Trigger a compute() to finish switching pages if necessary
2027 if (immediate) {
2028 computeScroll();
2029 }
2030
Winson Chung9c0565f2013-07-19 13:49:06 -07002031 // Defer loading associated pages until the scroll settles
2032 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2033
Adam Cohen7d30a372013-07-01 17:03:59 -07002034 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002035 invalidate();
2036 }
2037
Winson Chung321e9ee2010-08-09 13:37:56 -07002038 public void scrollLeft() {
2039 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002040 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002041 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002042 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002043 }
2044 }
2045
2046 public void scrollRight() {
2047 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002048 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002049 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002050 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002051 }
2052 }
2053
Winson Chung86f77532010-08-24 11:08:22 -07002054 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002055 int result = -1;
2056 if (v != null) {
2057 ViewParent vp = v.getParent();
2058 int count = getChildCount();
2059 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002060 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002061 return i;
2062 }
2063 }
2064 }
2065 return result;
2066 }
2067
2068 /**
2069 * @return True is long presses are still allowed for the current touch
2070 */
2071 public boolean allowLongPress() {
2072 return mAllowLongPress;
2073 }
2074
Michael Jurka0142d492010-08-25 17:46:15 -07002075 /**
2076 * Set true to allow long-press events to be triggered, usually checked by
2077 * {@link Launcher} to accept or block dpad-initiated long-presses.
2078 */
2079 public void setAllowLongPress(boolean allowLongPress) {
2080 mAllowLongPress = allowLongPress;
2081 }
2082
Winson Chung321e9ee2010-08-09 13:37:56 -07002083 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002084 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002085
2086 SavedState(Parcelable superState) {
2087 super(superState);
2088 }
2089
2090 private SavedState(Parcel in) {
2091 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002092 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002093 }
2094
2095 @Override
2096 public void writeToParcel(Parcel out, int flags) {
2097 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002098 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002099 }
2100
2101 public static final Parcelable.Creator<SavedState> CREATOR =
2102 new Parcelable.Creator<SavedState>() {
2103 public SavedState createFromParcel(Parcel in) {
2104 return new SavedState(in);
2105 }
2106
2107 public SavedState[] newArray(int size) {
2108 return new SavedState[size];
2109 }
2110 };
2111 }
2112
Winson Chungf314b0e2011-08-16 11:54:27 -07002113 protected void loadAssociatedPages(int page) {
2114 loadAssociatedPages(page, false);
2115 }
2116 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002117 if (mContentIsRefreshable) {
2118 final int count = getChildCount();
2119 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002120 int lowerPageBound = getAssociatedLowerPageBound(page);
2121 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002122 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2123 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002124 // First, clear any pages that should no longer be loaded
2125 for (int i = 0; i < count; ++i) {
2126 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002127 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002128 if (layout.getPageChildCount() > 0) {
2129 layout.removeAllViewsOnPage();
2130 }
2131 mDirtyPageContent.set(i, true);
2132 }
2133 }
2134 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002135 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002136 if ((i != page) && immediateAndOnly) {
2137 continue;
2138 }
Michael Jurka0142d492010-08-25 17:46:15 -07002139 if (lowerPageBound <= i && i <= upperPageBound) {
2140 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002141 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002142 mDirtyPageContent.set(i, false);
2143 }
Winson Chung86f77532010-08-24 11:08:22 -07002144 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002145 }
2146 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002147 }
2148 }
2149
Winson Chunge3193b92010-09-10 11:44:42 -07002150 protected int getAssociatedLowerPageBound(int page) {
2151 return Math.max(0, page - 1);
2152 }
2153 protected int getAssociatedUpperPageBound(int page) {
2154 final int count = getChildCount();
2155 return Math.min(page + 1, count - 1);
2156 }
2157
Winson Chung86f77532010-08-24 11:08:22 -07002158 /**
2159 * This method is called ONLY to synchronize the number of pages that the paged view has.
2160 * To actually fill the pages with information, implement syncPageItems() below. It is
2161 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2162 * and therefore, individual page items do not need to be updated in this method.
2163 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002164 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002165
2166 /**
2167 * This method is called to synchronize the items that are on a particular page. If views on
2168 * the page can be reused, then they should be updated within this method.
2169 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002170 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002171
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002172 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002173 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002174 }
2175 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002176 invalidatePageData(currentPage, false);
2177 }
2178 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002179 if (!mIsDataReady) {
2180 return;
2181 }
2182
Michael Jurka0142d492010-08-25 17:46:15 -07002183 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002184 // Force all scrolling-related behavior to end
2185 mScroller.forceFinished(true);
2186 mNextPage = INVALID_PAGE;
2187
Michael Jurka0142d492010-08-25 17:46:15 -07002188 // Update all the pages
2189 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002190
Winson Chung5a808352011-06-27 19:08:49 -07002191 // We must force a measure after we've loaded the pages to update the content width and
2192 // to determine the full scroll width
2193 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2194 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2195
2196 // Set a new page as the current page if necessary
2197 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002198 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002199 }
2200
Michael Jurka0142d492010-08-25 17:46:15 -07002201 // Mark each of the pages as dirty
2202 final int count = getChildCount();
2203 mDirtyPageContent.clear();
2204 for (int i = 0; i < count; ++i) {
2205 mDirtyPageContent.add(true);
2206 }
2207
2208 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002209 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002210 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002211 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002212 }
Winson Chung007c6982011-06-14 13:27:53 -07002213
Adam Cohen7d30a372013-07-01 17:03:59 -07002214 // Animate the drag view back to the original position
2215 void animateDragViewToOriginalPosition() {
2216 if (mDragView != null) {
2217 AnimatorSet anim = new AnimatorSet();
2218 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2219 anim.playTogether(
2220 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2221 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2222 anim.addListener(new AnimatorListenerAdapter() {
2223 @Override
2224 public void onAnimationEnd(Animator animation) {
2225 onPostReorderingAnimationCompleted();
2226 }
2227 });
2228 anim.start();
2229 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002230 }
2231
Adam Cohen7d30a372013-07-01 17:03:59 -07002232 // "Zooms out" the PagedView to reveal more side pages
2233 protected boolean zoomOut() {
2234 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2235 mZoomInOutAnim.cancel();
2236 }
2237
2238 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2239 mZoomInOutAnim = new AnimatorSet();
2240 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2241 mZoomInOutAnim.playTogether(
2242 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2243 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2244 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2245 @Override
2246 public void onAnimationStart(Animator animation) {
2247 // Show the delete drop target
2248 if (mDeleteDropTarget != null) {
2249 mDeleteDropTarget.setVisibility(View.VISIBLE);
2250 mDeleteDropTarget.animate().alpha(1f)
2251 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2252 .setListener(new AnimatorListenerAdapter() {
2253 @Override
2254 public void onAnimationStart(Animator animation) {
2255 mDeleteDropTarget.setAlpha(0f);
2256 }
2257 });
2258 }
2259 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002260 @Override
2261 public void onAnimationEnd(Animator animation) {
2262 // Update the visible pages
2263 invalidate();
2264 }
Adam Cohen7d30a372013-07-01 17:03:59 -07002265 });
2266 mZoomInOutAnim.start();
2267 return true;
2268 }
2269 return false;
2270 }
2271
2272 protected void onStartReordering() {
2273 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2274 mTouchState = TOUCH_STATE_REORDERING;
2275 mIsReordering = true;
2276
2277 // Mark all the non-widget pages as invisible
Winson Chungc9ca2982013-07-19 12:07:38 -07002278 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002279 for (int i = 0; i < getPageCount(); ++i) {
2280 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2281 getPageAt(i).setAlpha(0f);
2282 }
2283 }
2284
2285 // We must invalidate to trigger a redraw to update the layers such that the drag view
2286 // is always drawn on top
2287 invalidate();
2288 }
2289
2290 private void onPostReorderingAnimationCompleted() {
2291 // Trigger the callback when reordering has settled
2292 --mPostReorderingPreZoomInRemainingAnimationCount;
2293 if (mPostReorderingPreZoomInRunnable != null &&
2294 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2295 mPostReorderingPreZoomInRunnable.run();
2296 mPostReorderingPreZoomInRunnable = null;
2297 }
2298 }
2299
2300 protected void onEndReordering() {
2301 mIsReordering = false;
2302
2303 // Mark all the non-widget pages as visible again
Winson Chungc9ca2982013-07-19 12:07:38 -07002304 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002305 for (int i = 0; i < getPageCount(); ++i) {
2306 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2307 getPageAt(i).setAlpha(1f);
2308 }
2309 }
2310 }
2311
2312 public boolean startReordering() {
2313 int dragViewIndex = getPageNearestToCenterOfScreen();
2314 mTempVisiblePagesRange[0] = 0;
2315 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07002316 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002317 mReorderingStarted = true;
2318
2319 // Check if we are within the reordering range
2320 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2321 dragViewIndex <= mTempVisiblePagesRange[1]) {
2322 if (zoomOut()) {
2323 // Find the drag view under the pointer
2324 mDragView = getChildAt(dragViewIndex);
2325
2326 onStartReordering();
2327 }
2328 return true;
2329 }
2330 return false;
2331 }
2332
2333 boolean isReordering(boolean testTouchState) {
2334 boolean state = mIsReordering;
2335 if (testTouchState) {
2336 state &= (mTouchState == TOUCH_STATE_REORDERING);
2337 }
2338 return state;
2339 }
2340 void endReordering() {
2341 // For simplicity, we call endReordering sometimes even if reordering was never started.
2342 // In that case, we don't want to do anything.
2343 if (!mReorderingStarted) return;
2344 mReorderingStarted = false;
2345
2346 // If we haven't flung-to-delete the current child, then we just animate the drag view
2347 // back into position
2348 final Runnable onCompleteRunnable = new Runnable() {
2349 @Override
2350 public void run() {
2351 onEndReordering();
2352 }
2353 };
2354 if (!mDeferringForDelete) {
2355 mPostReorderingPreZoomInRunnable = new Runnable() {
2356 public void run() {
2357 zoomIn(onCompleteRunnable);
2358 };
2359 };
2360
2361 mPostReorderingPreZoomInRemainingAnimationCount =
2362 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2363 // Snap to the current page
2364 snapToPage(indexOfChild(mDragView), 0);
2365 // Animate the drag view back to the front position
2366 animateDragViewToOriginalPosition();
2367 } else {
2368 // Handled in post-delete-animation-callbacks
2369 }
2370 }
2371
2372 // "Zooms in" the PagedView to highlight the current page
2373 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2374 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2375 mZoomInOutAnim.cancel();
2376 }
2377 if (getScaleX() < 1f || getScaleY() < 1f) {
2378 mZoomInOutAnim = new AnimatorSet();
2379 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2380 mZoomInOutAnim.playTogether(
2381 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2382 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2383 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2384 @Override
2385 public void onAnimationStart(Animator animation) {
2386 // Hide the delete drop target
2387 if (mDeleteDropTarget != null) {
2388 mDeleteDropTarget.animate().alpha(0f)
2389 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2390 .setListener(new AnimatorListenerAdapter() {
2391 @Override
2392 public void onAnimationEnd(Animator animation) {
2393 mDeleteDropTarget.setVisibility(View.GONE);
2394 }
2395 });
2396 }
2397 }
2398 @Override
2399 public void onAnimationCancel(Animator animation) {
2400 mDragView = null;
2401 }
2402 @Override
2403 public void onAnimationEnd(Animator animation) {
2404 mDragView = null;
2405 if (onCompleteRunnable != null) {
2406 onCompleteRunnable.run();
2407 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002408 // Update the visible pages
2409 invalidate();
Adam Cohen7d30a372013-07-01 17:03:59 -07002410 }
2411 });
2412 mZoomInOutAnim.start();
2413 return true;
2414 } else {
2415 if (onCompleteRunnable != null) {
2416 onCompleteRunnable.run();
2417 }
2418 }
2419 return false;
2420 }
2421
2422 /*
2423 * Flinging to delete - IN PROGRESS
2424 */
2425 private PointF isFlingingToDelete() {
2426 ViewConfiguration config = ViewConfiguration.get(getContext());
2427 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2428
2429 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2430 // Do a quick dot product test to ensure that we are flinging upwards
2431 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2432 mVelocityTracker.getYVelocity());
2433 PointF upVec = new PointF(0f, -1f);
2434 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2435 (vel.length() * upVec.length()));
2436 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2437 return vel;
2438 }
2439 }
2440 return null;
2441 }
2442
2443 /**
2444 * Creates an animation from the current drag view along its current velocity vector.
2445 * For this animation, the alpha runs for a fixed duration and we update the position
2446 * progressively.
2447 */
2448 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2449 private View mDragView;
2450 private PointF mVelocity;
2451 private Rect mFrom;
2452 private long mPrevTime;
2453 private float mFriction;
2454
2455 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2456
2457 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2458 long startTime, float friction) {
2459 mDragView = dragView;
2460 mVelocity = vel;
2461 mFrom = from;
2462 mPrevTime = startTime;
2463 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2464 }
2465
2466 @Override
2467 public void onAnimationUpdate(ValueAnimator animation) {
2468 float t = ((Float) animation.getAnimatedValue()).floatValue();
2469 long curTime = AnimationUtils.currentAnimationTimeMillis();
2470
2471 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2472 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2473
2474 mDragView.setTranslationX(mFrom.left);
2475 mDragView.setTranslationY(mFrom.top);
2476 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2477
2478 mVelocity.x *= mFriction;
2479 mVelocity.y *= mFriction;
2480 mPrevTime = curTime;
2481 }
2482 };
2483
2484 private static final int ANIM_TAG_KEY = 100;
2485
2486 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2487 return new Runnable() {
2488 @Override
2489 public void run() {
2490 int dragViewIndex = indexOfChild(dragView);
2491
2492 // For each of the pages around the drag view, animate them from the previous
2493 // position to the new position in the layout (as a result of the drag view moving
2494 // in the layout)
2495 // NOTE: We can make an assumption here because we have side-bound pages that we
2496 // will always have pages to animate in from the left
Winson Chungc9ca2982013-07-19 12:07:38 -07002497 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002498 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2499 boolean slideFromLeft = (isLastWidgetPage ||
2500 dragViewIndex > mTempVisiblePagesRange[0]);
2501
2502 // Setup the scroll to the correct page before we swap the views
2503 if (slideFromLeft) {
2504 snapToPageImmediately(dragViewIndex - 1);
2505 }
2506
2507 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2508 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2509 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2510 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2511 ArrayList<Animator> animations = new ArrayList<Animator>();
2512 for (int i = lowerIndex; i <= upperIndex; ++i) {
2513 View v = getChildAt(i);
2514 // dragViewIndex < pageUnderPointIndex, so after we remove the
2515 // drag view all subsequent views to pageUnderPointIndex will
2516 // shift down.
2517 int oldX = 0;
2518 int newX = 0;
2519 if (slideFromLeft) {
2520 if (i == 0) {
2521 // Simulate the page being offscreen with the page spacing
2522 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2523 - mPageSpacing;
2524 } else {
2525 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2526 }
2527 newX = getViewportOffsetX() + getChildOffset(i);
2528 } else {
2529 oldX = getChildOffset(i) - getChildOffset(i - 1);
2530 newX = 0;
2531 }
2532
2533 // Animate the view translation from its old position to its new
2534 // position
2535 AnimatorSet anim = (AnimatorSet) v.getTag();
2536 if (anim != null) {
2537 anim.cancel();
2538 }
2539
2540 // Note: Hacky, but we want to skip any optimizations to not draw completely
2541 // hidden views
2542 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2543 v.setTranslationX(oldX - newX);
2544 anim = new AnimatorSet();
2545 anim.playTogether(
2546 ObjectAnimator.ofFloat(v, "translationX", 0f),
2547 ObjectAnimator.ofFloat(v, "alpha", 1f));
2548 animations.add(anim);
2549 v.setTag(ANIM_TAG_KEY, anim);
2550 }
2551
2552 AnimatorSet slideAnimations = new AnimatorSet();
2553 slideAnimations.playTogether(animations);
2554 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2555 slideAnimations.addListener(new AnimatorListenerAdapter() {
2556 @Override
2557 public void onAnimationEnd(Animator animation) {
2558 final Runnable onCompleteRunnable = new Runnable() {
2559 @Override
2560 public void run() {
2561 mDeferringForDelete = false;
2562 onEndReordering();
2563 onRemoveViewAnimationCompleted();
2564 }
2565 };
2566 zoomIn(onCompleteRunnable);
2567 }
2568 });
2569 slideAnimations.start();
2570
2571 removeView(dragView);
2572 onRemoveView(dragView, true);
2573 }
2574 };
2575 }
2576
2577 public void onFlingToDelete(PointF vel) {
2578 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2579
2580 // NOTE: Because it takes time for the first frame of animation to actually be
2581 // called and we expect the animation to be a continuation of the fling, we have
2582 // to account for the time that has elapsed since the fling finished. And since
2583 // we don't have a startDelay, we will always get call to update when we call
2584 // start() (which we want to ignore).
2585 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2586 private int mCount = -1;
2587 private long mStartTime;
2588 private float mOffset;
2589 /* Anonymous inner class ctor */ {
2590 mStartTime = startTime;
2591 }
2592
2593 @Override
2594 public float getInterpolation(float t) {
2595 if (mCount < 0) {
2596 mCount++;
2597 } else if (mCount == 0) {
2598 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2599 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2600 mCount++;
2601 }
2602 return Math.min(1f, mOffset + t);
2603 }
2604 };
2605
2606 final Rect from = new Rect();
2607 final View dragView = mDragView;
2608 from.left = (int) dragView.getTranslationX();
2609 from.top = (int) dragView.getTranslationY();
2610 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2611 from, startTime, FLING_TO_DELETE_FRICTION);
2612
2613 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2614
2615 // Create and start the animation
2616 ValueAnimator mDropAnim = new ValueAnimator();
2617 mDropAnim.setInterpolator(tInterpolator);
2618 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2619 mDropAnim.setFloatValues(0f, 1f);
2620 mDropAnim.addUpdateListener(updateCb);
2621 mDropAnim.addListener(new AnimatorListenerAdapter() {
2622 public void onAnimationEnd(Animator animation) {
2623 onAnimationEndRunnable.run();
2624 }
2625 });
2626 mDropAnim.start();
2627 mDeferringForDelete = true;
2628 }
2629
2630 /* Drag to delete */
2631 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2632 if (mDeleteDropTarget != null) {
2633 mAltTmpRect.set(0, 0, 0, 0);
2634 View parent = (View) mDeleteDropTarget.getParent();
2635 if (parent != null) {
2636 parent.getGlobalVisibleRect(mAltTmpRect);
2637 }
2638 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2639 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2640 return mTmpRect.contains(x, y);
2641 }
2642 return false;
2643 }
2644
2645 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2646
2647 private void onDropToDelete() {
2648 final View dragView = mDragView;
2649
2650 final float toScale = 0f;
2651 final float toAlpha = 0f;
2652
2653 // Create and start the complex animation
2654 ArrayList<Animator> animations = new ArrayList<Animator>();
2655 AnimatorSet motionAnim = new AnimatorSet();
2656 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2657 motionAnim.playTogether(
2658 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2659 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2660 animations.add(motionAnim);
2661
2662 AnimatorSet alphaAnim = new AnimatorSet();
2663 alphaAnim.setInterpolator(new LinearInterpolator());
2664 alphaAnim.playTogether(
2665 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2666 animations.add(alphaAnim);
2667
2668 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2669
2670 AnimatorSet anim = new AnimatorSet();
2671 anim.playTogether(animations);
2672 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2673 anim.addListener(new AnimatorListenerAdapter() {
2674 public void onAnimationEnd(Animator animation) {
2675 onAnimationEndRunnable.run();
2676 }
2677 });
2678 anim.start();
2679
2680 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002681 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002682
2683 /* Accessibility */
2684 @Override
2685 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2686 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002687 info.setScrollable(getPageCount() > 1);
2688 if (getCurrentPage() < getPageCount() - 1) {
2689 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2690 }
2691 if (getCurrentPage() > 0) {
2692 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2693 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002694 }
2695
2696 @Override
2697 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2698 super.onInitializeAccessibilityEvent(event);
2699 event.setScrollable(true);
2700 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2701 event.setFromIndex(mCurrentPage);
2702 event.setToIndex(mCurrentPage);
2703 event.setItemCount(getChildCount());
2704 }
2705 }
2706
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002707 @Override
2708 public boolean performAccessibilityAction(int action, Bundle arguments) {
2709 if (super.performAccessibilityAction(action, arguments)) {
2710 return true;
2711 }
2712 switch (action) {
2713 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2714 if (getCurrentPage() < getPageCount() - 1) {
2715 scrollRight();
2716 return true;
2717 }
2718 } break;
2719 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2720 if (getCurrentPage() > 0) {
2721 scrollLeft();
2722 return true;
2723 }
2724 } break;
2725 }
2726 return false;
2727 }
2728
Adam Cohen0ffac432013-07-10 11:19:26 -07002729 protected String getCurrentPageDescription() {
2730 return String.format(getContext().getString(R.string.default_scroll_format),
2731 getNextPage() + 1, getChildCount());
2732 }
2733
Winson Chungd11265e2011-08-30 13:37:23 -07002734 @Override
2735 public boolean onHoverEvent(android.view.MotionEvent event) {
2736 return true;
2737 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002738}