blob: e97bf8dcc9a05befa91bf73cefdbd295857f9282 [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen7d30a372013-07-01 17:03:59 -070027import android.content.res.Resources;
Adam Cohen9c4949e2010-10-05 12:27:22 -070028import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070029import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070030import android.graphics.Matrix;
31import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070032import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070033import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070034import android.os.Parcel;
35import android.os.Parcelable;
36import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070037import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070038import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080039import android.view.InputDevice;
40import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070041import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewGroup;
46import android.view.ViewParent;
Adam Cohen96d30a12013-07-16 18:13:21 -070047import android.view.ViewGroup.LayoutParams;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070049import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070050import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070051import android.view.animation.AnimationUtils;
52import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080053import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070054import android.view.animation.LinearInterpolator;
Adam Cohen96d30a12013-07-16 18:13:21 -070055import android.widget.FrameLayout;
Winson Chung321e9ee2010-08-09 13:37:56 -070056import android.widget.Scroller;
57
Winson Chung6a0f57d2011-06-29 20:10:49 -070058import java.util.ArrayList;
59
Winson Chung321e9ee2010-08-09 13:37:56 -070060/**
61 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070062 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070063 */
Michael Jurka8b805b12012-04-18 14:23:14 -070064public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070065 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070066 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070067 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070068
Winson Chung86f77532010-08-24 11:08:22 -070069 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070070 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070071
Adam Cohen7d30a372013-07-01 17:03:59 -070072 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070073 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070074 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070075
Adam Cohenb5ba0972011-09-07 18:02:31 -070076 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070077 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080078
Adam Cohenb64cb5a2011-02-15 13:53:42 -080079 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080080 // The page is moved more than halfway, automatically move to the next page on touch up.
81 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080082
Adam Cohen265b9a62011-12-07 14:37:18 -080083 // The following constants need to be scaled based on density. The scaled versions will be
84 // assigned to the corresponding member variables below.
85 private static final int FLING_THRESHOLD_VELOCITY = 500;
86 private static final int MIN_SNAP_VELOCITY = 1500;
87 private static final int MIN_FLING_VELOCITY = 250;
88
Adam Cohen7d30a372013-07-01 17:03:59 -070089 // We are disabling touch interaction of the widget region for factory ROM.
90 private static final boolean DISABLE_TOUCH_INTERACTION = false;
91 private static final boolean DISABLE_TOUCH_SIDE_PAGES = false;
Adam Cohendedbd962013-07-11 14:21:49 -070092 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070093
Winson Chung8aad6102012-05-11 16:27:49 -070094 static final int AUTOMATIC_PAGE_SPACING = -1;
95
Adam Cohen265b9a62011-12-07 14:37:18 -080096 protected int mFlingThresholdVelocity;
97 protected int mMinFlingVelocity;
98 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -070099
Adam Cohenb5ba0972011-09-07 18:02:31 -0700100 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700101 protected float mSmoothingTime;
102 protected float mTouchX;
103
104 protected boolean mFirstLayout = true;
105
106 protected int mCurrentPage;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700107 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700108
Michael Jurka0142d492010-08-25 17:46:15 -0700109 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800110 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700111 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700112 private VelocityTracker mVelocityTracker;
113
Adam Cohen7d30a372013-07-01 17:03:59 -0700114 private float mParentDownMotionX;
115 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700116 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700117 private float mDownMotionY;
118 private float mDownScrollX;
Michael Jurka7426c422010-11-11 15:23:47 -0800119 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800120 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800121 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800122 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700123 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700124
125 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700126
Michael Jurka0142d492010-08-25 17:46:15 -0700127 protected final static int TOUCH_STATE_REST = 0;
128 protected final static int TOUCH_STATE_SCROLLING = 1;
129 protected final static int TOUCH_STATE_PREV_PAGE = 2;
130 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700131 protected final static int TOUCH_STATE_REORDERING = 4;
132
Adam Cohene45440e2010-10-14 18:33:38 -0700133 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700134
Michael Jurka0142d492010-08-25 17:46:15 -0700135 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700136 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700137
Michael Jurka0142d492010-08-25 17:46:15 -0700138 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700139
Michael Jurka7426c422010-11-11 15:23:47 -0800140 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700141 private int mPagingTouchSlop;
142 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700143 protected int mPageSpacing;
144 protected int mPageLayoutPaddingTop;
145 protected int mPageLayoutPaddingBottom;
146 protected int mPageLayoutPaddingLeft;
147 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700148 protected int mPageLayoutWidthGap;
149 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700150 protected int mCellCountX = 0;
151 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700152 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800153 protected boolean mAllowOverScroll = true;
154 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800155 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700156 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700157
Michael Jurka8b805b12012-04-18 14:23:14 -0700158 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800159 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
160 // the screens from continuing to translate beyond the normal bounds.
161 protected int mOverScrollX;
162
Michael Jurka5f1c5092010-09-03 14:15:02 -0700163 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700164
Michael Jurka5f1c5092010-09-03 14:15:02 -0700165 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700166
Winson Chung86f77532010-08-24 11:08:22 -0700167 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700168
Michael Jurkae326f182011-11-21 14:05:46 -0800169 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700170
Michael Jurka0142d492010-08-25 17:46:15 -0700171 // If true, syncPages and syncPageItems will be called to refresh pages
172 protected boolean mContentIsRefreshable = true;
173
174 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700175 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700176
177 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
178 // to switch to a new page
179 protected boolean mUsePagingTouchSlop = true;
180
Michael Jurka8b805b12012-04-18 14:23:14 -0700181 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700182 // (SmoothPagedView does this)
183 protected boolean mDeferScrollUpdate = false;
184
Patrick Dubroy1262e362010-10-06 15:49:50 -0700185 protected boolean mIsPageMoving = false;
186
Winson Chungf0ea4d32011-06-06 14:27:16 -0700187 // All syncs and layout passes are deferred until data is ready.
188 protected boolean mIsDataReady = false;
189
Adam Cohen7d30a372013-07-01 17:03:59 -0700190 protected boolean mAllowLongPress = true;
191
Winson Chungd2be3812013-07-16 11:11:32 -0700192 // Page Indicator
193 private int mPageIndicatorViewId;
194 private PageIndicator mPageIndicator;
Winson Chung007c6982011-06-14 13:27:53 -0700195
Adam Cohen7d30a372013-07-01 17:03:59 -0700196 // The viewport whether the pages are to be contained (the actual view may be larger than the
197 // viewport)
198 private Rect mViewport = new Rect();
199
200 // Reordering
201 // We use the min scale to determine how much to expand the actually PagedView measured
202 // dimensions such that when we are zoomed out, the view is not clipped
203 private int REORDERING_DROP_REPOSITION_DURATION = 200;
204 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
205 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
206 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 300;
207 private float REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE = 0.1f;
208 private long REORDERING_DELETE_DROP_TARGET_FADE_DURATION = 150;
209 private float mMinScale = 1f;
210 protected View mDragView;
211 protected AnimatorSet mZoomInOutAnim;
212 private Runnable mSidePageHoverRunnable;
213 private int mSidePageHoverIndex = -1;
214 // This variable's scope is only for the duration of startReordering() and endReordering()
215 private boolean mReorderingStarted = false;
216 // This variable's scope is for the duration of startReordering() and after the zoomIn()
217 // animation after endReordering()
218 private boolean mIsReordering;
219 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
220 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
221 private int mPostReorderingPreZoomInRemainingAnimationCount;
222 private Runnable mPostReorderingPreZoomInRunnable;
223
224 // Edge swiping
225 private boolean mOnlyAllowEdgeSwipes = false;
226 private boolean mDownEventOnEdge = false;
227 private int mEdgeSwipeRegionSize = 0;
228
229 // Convenience/caching
230 private Matrix mTmpInvMatrix = new Matrix();
231 private float[] mTmpPoint = new float[2];
232 private Rect mTmpRect = new Rect();
233 private Rect mAltTmpRect = new Rect();
234
235 // Fling to delete
236 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
237 private float FLING_TO_DELETE_FRICTION = 0.035f;
238 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
239 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
240 protected int mFlingToDeleteThresholdVelocity = -1400;
241 // Drag to delete
242 private boolean mDeferringForDelete = false;
243 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
244 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
245
246 // Drop to delete
247 private View mDeleteDropTarget;
248
249 private boolean mAutoComputePageSpacing = false;
250 private boolean mRecomputePageSpacing = false;
251
252 // Bouncer
253 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700254
Winson Chung86f77532010-08-24 11:08:22 -0700255 public interface PageSwitchListener {
256 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700257 }
258
Winson Chung321e9ee2010-08-09 13:37:56 -0700259 public PagedView(Context context) {
260 this(context, null);
261 }
262
263 public PagedView(Context context, AttributeSet attrs) {
264 this(context, attrs, 0);
265 }
266
267 public PagedView(Context context, AttributeSet attrs, int defStyle) {
268 super(context, attrs, defStyle);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700269 TypedArray a = context.obtainStyledAttributes(attrs,
270 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800271 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700272 if (mPageSpacing < 0) {
273 mAutoComputePageSpacing = mRecomputePageSpacing = true;
274 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700275 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800276 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700277 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800278 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700279 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800280 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700281 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800282 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700283 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700284 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700285 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700286 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700287 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700288 a.recycle();
289
Winson Chung321e9ee2010-08-09 13:37:56 -0700290 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700291 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700292 }
293
294 /**
295 * Initializes various states for this workspace.
296 */
Michael Jurka0142d492010-08-25 17:46:15 -0700297 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700298 mDirtyPageContent = new ArrayList<Boolean>();
299 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800300 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700301 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700302 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700303
304 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700305 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700306 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
307 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700308 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800309
Adam Cohen7d30a372013-07-01 17:03:59 -0700310 // Scale the fling-to-delete threshold by the density
311 mFlingToDeleteThresholdVelocity =
312 (int) (mFlingToDeleteThresholdVelocity * mDensity);
313
Adam Cohen265b9a62011-12-07 14:37:18 -0800314 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
315 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
316 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700317 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700318 }
319
Winson Chungd2be3812013-07-16 11:11:32 -0700320 protected void onAttachedToWindow() {
321 // Hook up the page indicator
322 ViewGroup parent = (ViewGroup) getParent();
323 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
324 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
325 mPageIndicator.removeAllMarkers();
326 mPageIndicator.addMarkers(getChildCount());
327 }
328 }
329
330 protected void onDetachedFromWindow() {
331 // Unhook the page indicator
332 mPageIndicator = null;
333 }
334
Adam Cohen7d30a372013-07-01 17:03:59 -0700335 void setDeleteDropTarget(View v) {
336 mDeleteDropTarget = v;
337 }
338
339 // Convenience methods to map points from self to parent and vice versa
340 float[] mapPointFromViewToParent(View v, float x, float y) {
341 mTmpPoint[0] = x;
342 mTmpPoint[1] = y;
343 v.getMatrix().mapPoints(mTmpPoint);
344 mTmpPoint[0] += v.getLeft();
345 mTmpPoint[1] += v.getTop();
346 return mTmpPoint;
347 }
348 float[] mapPointFromParentToView(View v, float x, float y) {
349 mTmpPoint[0] = x - v.getLeft();
350 mTmpPoint[1] = y - v.getTop();
351 v.getMatrix().invert(mTmpInvMatrix);
352 mTmpInvMatrix.mapPoints(mTmpPoint);
353 return mTmpPoint;
354 }
355
356 void updateDragViewTranslationDuringDrag() {
357 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
358 float y = mLastMotionY - mDownMotionY;
359 mDragView.setTranslationX(x);
360 mDragView.setTranslationY(y);
361
362 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
363 }
364
365 public void setMinScale(float f) {
366 mMinScale = f;
367 requestLayout();
368 }
369
370 @Override
371 public void setScaleX(float scaleX) {
372 super.setScaleX(scaleX);
373 if (isReordering(true)) {
374 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
375 mLastMotionX = p[0];
376 mLastMotionY = p[1];
377 updateDragViewTranslationDuringDrag();
378 }
379 }
380
381 // Convenience methods to get the actual width/height of the PagedView (since it is measured
382 // to be larger to account for the minimum possible scale)
383 int getViewportWidth() {
384 return mViewport.width();
385 }
386 int getViewportHeight() {
387 return mViewport.height();
388 }
389
390 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
391 // PagedView both horizontally and vertically
392 int getViewportOffsetX() {
393 return (getMeasuredWidth() - getViewportWidth()) / 2;
394 }
395
396 int getViewportOffsetY() {
397 return (getMeasuredHeight() - getViewportHeight()) / 2;
398 }
399
Adam Cohenedb40762013-07-18 16:45:45 -0700400 PageIndicator getPageIndicator() {
401 return mPageIndicator;
402 }
403
Winson Chung86f77532010-08-24 11:08:22 -0700404 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
405 mPageSwitchListener = pageSwitchListener;
406 if (mPageSwitchListener != null) {
407 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700408 }
409 }
410
411 /**
Winson Chung52aee602013-01-30 12:01:02 -0800412 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
413 */
414 public boolean isLayoutRtl() {
415 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
416 }
417
418 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700419 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
420 * out pages.
421 */
422 protected void setDataIsReady() {
423 mIsDataReady = true;
424 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700425
Winson Chungf0ea4d32011-06-06 14:27:16 -0700426 protected boolean isDataReady() {
427 return mIsDataReady;
428 }
429
430 /**
Winson Chung86f77532010-08-24 11:08:22 -0700431 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700432 *
Winson Chung86f77532010-08-24 11:08:22 -0700433 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700434 */
Winson Chung86f77532010-08-24 11:08:22 -0700435 int getCurrentPage() {
436 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700437 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700438
Winson Chung360e63f2012-04-27 13:48:05 -0700439 int getNextPage() {
440 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
441 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700442
Winson Chung86f77532010-08-24 11:08:22 -0700443 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700444 return getChildCount();
445 }
446
Winson Chung86f77532010-08-24 11:08:22 -0700447 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700448 return getChildAt(index);
449 }
450
Adam Cohenae4f1552011-10-20 00:15:42 -0700451 protected int indexToPage(int index) {
452 return index;
453 }
454
Winson Chung321e9ee2010-08-09 13:37:56 -0700455 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800456 * Updates the scroll of the current page immediately to its final scroll position. We use this
457 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
458 * the previous tab page.
459 */
460 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700461 // If the current page is invalid, just reset the scroll position to zero
462 int newX = 0;
463 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700464 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700465 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800466 scrollTo(newX, 0);
467 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800468 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800469 }
470
471 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700472 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
473 * ends, {@link #resumeScrolling()} should be called, along with
474 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
475 */
476 void pauseScrolling() {
477 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700478 }
479
480 /**
481 * Enables scrolling again.
482 * @see #pauseScrolling()
483 */
484 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700485 }
486 /**
Winson Chung86f77532010-08-24 11:08:22 -0700487 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700488 */
Winson Chung86f77532010-08-24 11:08:22 -0700489 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800490 if (!mScroller.isFinished()) {
491 mScroller.abortAnimation();
492 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800493 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
494 // the default
495 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800496 return;
497 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700498
Adam Cohene61a9a22013-06-11 15:45:31 -0700499 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700500 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700501 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700502 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800503 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700504 }
505
Michael Jurka0142d492010-08-25 17:46:15 -0700506 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700507 if (mPageSwitchListener != null) {
508 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700509 }
Winson Chungd2be3812013-07-16 11:11:32 -0700510
511 // Update the page indicator (when we aren't reordering)
512 if (mPageIndicator != null && !isReordering(false)) {
513 mPageIndicator.setActiveMarker(getNextPage());
514 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700515 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800516 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700517 if (!mIsPageMoving) {
518 mIsPageMoving = true;
519 onPageBeginMoving();
520 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700521 }
522
Michael Jurkace7e05f2011-02-01 22:02:35 -0800523 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700524 if (mIsPageMoving) {
525 mIsPageMoving = false;
526 onPageEndMoving();
527 }
Michael Jurka0142d492010-08-25 17:46:15 -0700528 }
529
Adam Cohen26976d92011-03-22 15:33:33 -0700530 protected boolean isPageMoving() {
531 return mIsPageMoving;
532 }
533
Michael Jurka0142d492010-08-25 17:46:15 -0700534 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700535 protected void onPageBeginMoving() {
536 }
537
538 // a method that subclasses can override to add behavior
539 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700540 }
541
Winson Chung321e9ee2010-08-09 13:37:56 -0700542 /**
Winson Chung86f77532010-08-24 11:08:22 -0700543 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700544 *
545 * @param l The listener used to respond to long clicks.
546 */
547 @Override
548 public void setOnLongClickListener(OnLongClickListener l) {
549 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700550 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700551 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700552 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700553 }
554 }
555
556 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800557 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700558 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800559 }
560
561 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700562 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700563 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800564 mUnboundedScrollX = x;
565
Adam Cohen0ffac432013-07-10 11:19:26 -0700566 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
567 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
568 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800569 super.scrollTo(0, y);
570 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700571 if (isRtl) {
572 overScroll(x - mMaxScrollX);
573 } else {
574 overScroll(x);
575 }
Adam Cohen68d73932010-11-15 10:50:58 -0800576 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700577 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800578 super.scrollTo(mMaxScrollX, y);
579 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700580 if (isRtl) {
581 overScroll(x);
582 } else {
583 overScroll(x - mMaxScrollX);
584 }
Adam Cohen68d73932010-11-15 10:50:58 -0800585 }
586 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800587 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800588 super.scrollTo(x, y);
589 }
590
Michael Jurka0142d492010-08-25 17:46:15 -0700591 mTouchX = x;
592 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700593
594 // Update the last motion events when scrolling
595 if (isReordering(true)) {
596 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
597 mLastMotionX = p[0];
598 mLastMotionY = p[1];
599 updateDragViewTranslationDuringDrag();
600 }
Michael Jurka0142d492010-08-25 17:46:15 -0700601 }
602
603 // we moved this functionality to a helper function so SmoothPagedView can reuse it
604 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700605 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700606 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700607 if (getScrollX() != mScroller.getCurrX()
608 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700609 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700610 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
611 }
Michael Jurka0142d492010-08-25 17:46:15 -0700612 invalidate();
613 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700614 } else if (mNextPage != INVALID_PAGE) {
615 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700616 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700617 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700618
Adam Cohen73aa9752010-11-24 16:26:58 -0800619 // We don't want to trigger a page end moving unless the page has settled
620 // and the user has stopped scrolling
621 if (mTouchState == TOUCH_STATE_REST) {
622 pageEndMoving();
623 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700624
Adam Cohen7d30a372013-07-01 17:03:59 -0700625 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700626 // Notify the user when the page changes
627 AccessibilityManager accessibilityManager = (AccessibilityManager)
628 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
629 if (accessibilityManager.isEnabled()) {
630 AccessibilityEvent ev =
631 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
632 ev.getText().add(getCurrentPageDescription());
633 sendAccessibilityEventUnchecked(ev);
634 }
Michael Jurka0142d492010-08-25 17:46:15 -0700635 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700636 }
Michael Jurka0142d492010-08-25 17:46:15 -0700637 return false;
638 }
639
640 @Override
641 public void computeScroll() {
642 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700643 }
644
Adam Cohen7d30a372013-07-01 17:03:59 -0700645 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
646 return mTopAlignPageWhenShrinkingForBouncer;
647 }
648
Adam Cohen96d30a12013-07-16 18:13:21 -0700649 public static class LayoutParams extends ViewGroup.LayoutParams {
650 public boolean isFullScreenPage = false;
651
652 /**
653 * {@inheritDoc}
654 */
655 public LayoutParams(int width, int height) {
656 super(width, height);
657 }
658
659 public LayoutParams(ViewGroup.LayoutParams source) {
660 super(source);
661 }
662 }
663
664 protected LayoutParams generateDefaultLayoutParams() {
665 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
666 }
667
Adam Cohenedb40762013-07-18 16:45:45 -0700668 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700669 LayoutParams lp = generateDefaultLayoutParams();
670 lp.isFullScreenPage = true;
671 super.addView(page, 0, lp);
672 }
673
Winson Chung321e9ee2010-08-09 13:37:56 -0700674 @Override
675 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700676 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700677 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
678 return;
679 }
680
Adam Cohen7d30a372013-07-01 17:03:59 -0700681 // We measure the dimensions of the PagedView to be larger than the pages so that when we
682 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700683 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
684 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
685 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700686 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700687 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
688 // viewport, we can be at most one and a half screens offset once we scale down
689 DisplayMetrics dm = getResources().getDisplayMetrics();
690 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
691 int parentWidthSize = (int) (1.5f * maxSize);
692 int parentHeightSize = maxSize;
693 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
694 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
695 mViewport.set(0, 0, widthSize, heightSize);
696
697 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
698 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
699 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700700 }
701
Winson Chung8aad6102012-05-11 16:27:49 -0700702 // Return early if we aren't given a proper dimension
703 if (widthSize <= 0 || heightSize <= 0) {
704 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
705 return;
706 }
707
Adam Lesinski6b879f02010-11-04 16:15:23 -0700708 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
709 * of the All apps view on XLarge displays to not take up more space then it needs. Width
710 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
711 * each page to have the same width.
712 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700713 final int verticalPadding = getPaddingTop() + getPaddingBottom();
714 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700715
716 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700717 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700718 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700719 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
720 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
721 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
722 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700723 final int childCount = getChildCount();
724 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700725 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700726 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700727 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
728
729 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700730 int childHeightMode;
731 int childWidth;
732 int childHeight;
733
734 if (!lp.isFullScreenPage) {
735 if (lp.width == LayoutParams.WRAP_CONTENT) {
736 childWidthMode = MeasureSpec.AT_MOST;
737 } else {
738 childWidthMode = MeasureSpec.EXACTLY;
739 }
740
741 if (lp.height == LayoutParams.WRAP_CONTENT) {
742 childHeightMode = MeasureSpec.AT_MOST;
743 } else {
744 childHeightMode = MeasureSpec.EXACTLY;
745 }
746
747 childWidth = widthSize - horizontalPadding;
748 childHeight = heightSize - verticalPadding;
749
Michael Jurka5f1c5092010-09-03 14:15:02 -0700750 } else {
751 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700752 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700753
754 childWidth = getViewportWidth();
755 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700756 }
757
758 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700759 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
760 final int childHeightMeasureSpec =
761 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700762 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700763 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700764 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700765
Winson Chunga128a7b2012-04-30 15:23:15 -0700766 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700767 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700768 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700769 // The gap between pages in the PagedView should be equal to the gap from the page
770 // to the edge of the screen (so it is not visible in the current screen). To
771 // account for unequal padding on each side of the paged view, we take the maximum
772 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700773 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700774 int spacing = Math.max(offset, widthSize - offset -
775 getChildAt(0).getMeasuredWidth());
776 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700777 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700778 }
779 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700780 }
781
Adam Cohen60b07122011-11-14 17:26:06 -0800782 public void setPageSpacing(int pageSpacing) {
783 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700784 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800785 }
786
Winson Chung321e9ee2010-08-09 13:37:56 -0700787 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700788 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700789 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700790 return;
791 }
792
Winson Chung785d2eb2011-04-14 16:08:02 -0700793 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700794 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700795
Adam Cohenedb40762013-07-18 16:45:45 -0700796 int screenWidth = getViewportWidth();
797
Adam Cohen7d30a372013-07-01 17:03:59 -0700798 int offsetX = getViewportOffsetX();
799 int offsetY = getViewportOffsetY();
800
801 // Update the viewport offsets
802 mViewport.offset(offsetX, offsetY);
803
Adam Cohen0ffac432013-07-10 11:19:26 -0700804 final boolean isRtl = isLayoutRtl();
805
806 final int startIndex = isRtl ? childCount - 1 : 0;
807 final int endIndex = isRtl ? -1 : childCount;
808 final int delta = isRtl ? -1 : 1;
809
Adam Cohen7d30a372013-07-01 17:03:59 -0700810 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700811 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
812
813 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
814 mPageScrolls = new int[getChildCount()];
815 }
816
Adam Cohen0ffac432013-07-10 11:19:26 -0700817 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700818 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700819 LayoutParams lp = (LayoutParams) child.getLayoutParams();
820 int childTop;
821
822 if (lp.isFullScreenPage) {
823 childTop = offsetY;
824 } else {
825 childTop = offsetY + getPaddingTop();
826 if (mCenterPagesVertically) {
827 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
828 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700829 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700830
Winson Chung321e9ee2010-08-09 13:37:56 -0700831 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700832 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700833 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800834
Winson Chung785d2eb2011-04-14 16:08:02 -0700835 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700836 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800837 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700838
839 // We assume the left and right padding are equal, and hence center the pages
840 // horizontally
841 int scrollOffset = false ? 0 : (getViewportWidth() - childWidth) / 2;
842 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
843
Adam Cohen9c4949e2010-10-05 12:27:22 -0700844 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700845 }
846 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700847
848 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
849 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800850 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700851 setHorizontalScrollBarEnabled(true);
852 mFirstLayout = false;
853 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700854
855 if (childCount > 0) {
856 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700857 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700858 } else {
859 mMaxScrollX = 0;
860 }
861
862 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
863 !mDeferringForDelete) {
864 setCurrentPage(getNextPage());
865 }
866 mChildCountOnLastLayout = getChildCount();
Winson Chunge3193b92010-09-10 11:44:42 -0700867 }
868
Adam Cohenf34bab52010-09-30 14:11:56 -0700869 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700870 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
871
872 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700873 for (int i = 0; i < getChildCount(); i++) {
874 View child = getChildAt(i);
875 if (child != null) {
876 float scrollProgress = getScrollProgress(screenCenter, child, i);
877 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800878 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700879 }
880 }
881 invalidate();
882 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700883 }
884
Winson Chunge3193b92010-09-10 11:44:42 -0700885 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700886 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700887 // Update the page indicator, we don't update the page indicator as we
888 // add/remove pages
889 if (mPageIndicator != null && !isReordering(false)) {
890 mPageIndicator.addMarker(indexOfChild(child));
891 }
892
Adam Cohen2591f6a2011-10-25 14:36:40 -0700893 // This ensures that when children are added, they get the correct transforms / alphas
894 // in accordance with any scroll effects.
895 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700896 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700897
Adam Cohen2591f6a2011-10-25 14:36:40 -0700898 invalidate();
899 }
900
Michael Jurka8b805b12012-04-18 14:23:14 -0700901 @Override
902 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700903 mForceScreenScrolled = true;
904 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700905 }
906
Winson Chungd2be3812013-07-16 11:11:32 -0700907 private void removeMarkerForView(int index) {
908 // Update the page indicator, we don't update the page indicator as we
909 // add/remove pages
910 if (mPageIndicator != null && !isReordering(false)) {
911 mPageIndicator.removeMarker(index);
912 }
913 }
914
915 @Override
916 public void removeView(View v) {
917 // XXX: We should find a better way to hook into this before the view
918 // gets removed form its parent...
919 removeMarkerForView(indexOfChild(v));
920 super.removeView(v);
921 }
922 @Override
923 public void removeViewInLayout(View v) {
924 // XXX: We should find a better way to hook into this before the view
925 // gets removed form its parent...
926 removeMarkerForView(indexOfChild(v));
927 super.removeViewInLayout(v);
928 }
929 @Override
930 public void removeViewAt(int index) {
931 // XXX: We should find a better way to hook into this before the view
932 // gets removed form its parent...
933 removeViewAt(index);
934 super.removeViewAt(index);
935 }
936 @Override
937 public void removeAllViewsInLayout() {
938 // Update the page indicator, we don't update the page indicator as we
939 // add/remove pages
940 if (mPageIndicator != null) {
941 mPageIndicator.removeAllMarkers();
942 }
943
944 super.removeAllViewsInLayout();
945 }
946
Adam Cohen73894962011-10-31 13:17:17 -0700947 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700948 if (index < 0 || index > getChildCount() - 1) return 0;
949
Adam Cohen0ffac432013-07-10 11:19:26 -0700950 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700951
Adam Cohenf698c6e2013-07-17 18:44:25 -0700952 if (isRtl) index = getChildCount() - index - 1;
953 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -0700954
Adam Cohenf698c6e2013-07-17 18:44:25 -0700955 return offset;
Adam Cohen73894962011-10-31 13:17:17 -0700956 }
957
Adam Cohen7d30a372013-07-01 17:03:59 -0700958 void boundByReorderablePages(boolean isReordering, int[] range) {
959 // Do nothing
960 }
961
962 // TODO: Fix this
Michael Jurkadde558b2011-11-09 22:09:06 -0800963 protected void getVisiblePages(int[] range) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700964 range[0] = 0;
965 range[1] = getPageCount() - 1;
966
967 /*
Michael Jurka0142d492010-08-25 17:46:15 -0700968 final int pageCount = getChildCount();
Michael Jurka4ff7d792012-04-02 03:46:50 -0700969
Michael Jurkac4fb9172010-09-02 17:19:20 -0700970 if (pageCount > 0) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700971 final int screenWidth = getViewportWidth();
972 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -0700973 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -0700974 int offsetX = getViewportOffsetX() + getScrollX();
Michael Jurka47f74742012-03-02 13:39:13 -0800975 View currPage = getPageAt(leftScreen);
Adam Cohen7d30a372013-07-01 17:03:59 -0700976 while (leftScreen < pageCount - 1 &&
Michael Jurka8b805b12012-04-18 14:23:14 -0700977 currPage.getX() + currPage.getWidth() -
Adam Cohen7d30a372013-07-01 17:03:59 -0700978 currPage.getPaddingRight() < offsetX) {
979 leftScreen++;
Michael Jurka47f74742012-03-02 13:39:13 -0800980 currPage = getPageAt(leftScreen);
Michael Jurkac4fb9172010-09-02 17:19:20 -0700981 }
982 rightScreen = leftScreen;
Adam Cohen7d30a372013-07-01 17:03:59 -0700983 currPage = getPageAt(rightScreen + 1);
984 while (rightScreen < pageCount - 1 &&
985 currPage.getX() - currPage.getPaddingLeft() < offsetX + screenWidth) {
986 rightScreen++;
987 currPage = getPageAt(rightScreen + 1);
Michael Jurkac4fb9172010-09-02 17:19:20 -0700988 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700989
990 // TEMP: this is a hacky way to ensure that animations to new pages are not clipped
991 // because we don't draw them while scrolling?
992 range[0] = Math.max(0, leftScreen - 1);
993 range[1] = Math.min(rightScreen + 1, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -0800994 } else {
995 range[0] = -1;
996 range[1] = -1;
997 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700998 */
Michael Jurkadde558b2011-11-09 22:09:06 -0800999 }
1000
Michael Jurka920d7f42012-05-14 16:29:55 -07001001 protected boolean shouldDrawChild(View child) {
1002 return child.getAlpha() > 0;
1003 }
1004
Michael Jurkadde558b2011-11-09 22:09:06 -08001005 @Override
1006 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001007 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001008 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1009 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001010 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001011
1012 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001013 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1014 // set it for the next frame
1015 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001016 screenScrolled(screenCenter);
1017 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001018 }
1019
1020 // Find out which screens are visible; as an optimization we only call draw on them
1021 final int pageCount = getChildCount();
1022 if (pageCount > 0) {
1023 getVisiblePages(mTempVisiblePagesRange);
1024 final int leftScreen = mTempVisiblePagesRange[0];
1025 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001026 if (leftScreen != -1 && rightScreen != -1) {
1027 final long drawingTime = getDrawingTime();
1028 // Clip to the bounds
1029 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001030 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1031 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001032
Adam Cohen7d30a372013-07-01 17:03:59 -07001033 // Draw all the children, leaving the drag view for last
1034 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001035 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001036 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001037 if (mForceDrawAllChildrenNextFrame ||
1038 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001039 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001040 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001041 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001042 // Draw the drag view on top (if there is one)
1043 if (mDragView != null) {
1044 drawChild(canvas, mDragView, drawingTime);
1045 }
1046
Michael Jurka5e368ff2012-05-14 23:13:15 -07001047 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001048 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001049 }
Michael Jurka0142d492010-08-25 17:46:15 -07001050 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001051 }
1052
1053 @Override
1054 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001055 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001056 if (page != mCurrentPage || !mScroller.isFinished()) {
1057 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001058 return true;
1059 }
1060 return false;
1061 }
1062
1063 @Override
1064 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001065 int focusablePage;
1066 if (mNextPage != INVALID_PAGE) {
1067 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001068 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001069 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001070 }
Winson Chung86f77532010-08-24 11:08:22 -07001071 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001072 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001073 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001074 }
1075 return false;
1076 }
1077
1078 @Override
1079 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001080 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001081 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001082 if (getCurrentPage() > 0) {
1083 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001084 return true;
1085 }
1086 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001087 if (getCurrentPage() < getPageCount() - 1) {
1088 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001089 return true;
1090 }
1091 }
1092 return super.dispatchUnhandledMove(focused, direction);
1093 }
1094
1095 @Override
1096 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001097 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001098 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001099 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001100 }
1101 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001102 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001103 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001104 }
1105 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001106 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001107 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001108 }
1109 }
1110 }
1111
1112 /**
1113 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001114 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001115 *
Winson Chung86f77532010-08-24 11:08:22 -07001116 * This happens when live folders requery, and if they're off page, they
1117 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001118 */
1119 @Override
1120 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001121 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001122 View v = focused;
1123 while (true) {
1124 if (v == current) {
1125 super.focusableViewAvailable(focused);
1126 return;
1127 }
1128 if (v == this) {
1129 return;
1130 }
1131 ViewParent parent = v.getParent();
1132 if (parent instanceof View) {
1133 v = (View)v.getParent();
1134 } else {
1135 return;
1136 }
1137 }
1138 }
1139
1140 /**
1141 * {@inheritDoc}
1142 */
1143 @Override
1144 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1145 if (disallowIntercept) {
1146 // We need to make sure to cancel our long press if
1147 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001148 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001149 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001150 }
1151 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1152 }
1153
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001154 /**
1155 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1156 */
1157 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001158 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001159 if (isLayoutRtl()) {
1160 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001161 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001162 }
Adam Cohenedb40762013-07-18 16:45:45 -07001163 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001164 }
1165
1166 /**
1167 * Return true if a tap at (x, y) should trigger a flip to the next page.
1168 */
1169 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001170 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001171 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001172 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001173 }
1174 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001175 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001176 }
Winson Chung52aee602013-01-30 12:01:02 -08001177
Adam Cohen7d30a372013-07-01 17:03:59 -07001178 /** Returns whether x and y originated within the buffered viewport */
1179 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1180 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1181 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1182 return mTmpRect.contains(x, y);
1183 }
1184
1185 /** Returns whether x and y originated within the current page view bounds */
1186 private boolean isTouchPointInCurrentPage(int x, int y) {
1187 View v = getPageAt(getCurrentPage());
1188 if (v != null) {
1189 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1190 v.getBottom());
1191 return mTmpRect.contains(x, y);
1192 }
1193 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001194 }
1195
Winson Chung321e9ee2010-08-09 13:37:56 -07001196 @Override
1197 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001198 if (DISABLE_TOUCH_INTERACTION) {
1199 return false;
1200 }
1201
Winson Chung321e9ee2010-08-09 13:37:56 -07001202 /*
1203 * This method JUST determines whether we want to intercept the motion.
1204 * If we return true, onTouchEvent will be called and we do the actual
1205 * scrolling there.
1206 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001207 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001208
Winson Chung45e1d6e2010-11-09 17:19:49 -08001209 // Skip touch handling if there are no pages to swipe
1210 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1211
Winson Chung321e9ee2010-08-09 13:37:56 -07001212 /*
1213 * Shortcut the most recurring case: the user is in the dragging
1214 * state and he is moving his finger. We want to intercept this
1215 * motion.
1216 */
1217 final int action = ev.getAction();
1218 if ((action == MotionEvent.ACTION_MOVE) &&
1219 (mTouchState == TOUCH_STATE_SCROLLING)) {
1220 return true;
1221 }
1222
Winson Chung321e9ee2010-08-09 13:37:56 -07001223 switch (action & MotionEvent.ACTION_MASK) {
1224 case MotionEvent.ACTION_MOVE: {
1225 /*
1226 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1227 * whether the user has moved far enough from his original down touch.
1228 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001229 if (mActivePointerId != INVALID_POINTER) {
1230 determineScrollingStart(ev);
1231 break;
1232 }
1233 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1234 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1235 // i.e. fall through to the next case (don't break)
1236 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1237 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001238 }
1239
1240 case MotionEvent.ACTION_DOWN: {
1241 final float x = ev.getX();
1242 final float y = ev.getY();
1243 // Remember location of down touch
1244 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001245 mDownMotionY = y;
1246 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001247 mLastMotionX = x;
1248 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001249 float[] p = mapPointFromViewToParent(this, x, y);
1250 mParentDownMotionX = p[0];
1251 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001252 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001253 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001254 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001255
1256 // Determine if the down event is within the threshold to be an edge swipe
1257 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1258 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1259 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1260 mDownEventOnEdge = true;
1261 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001262
1263 /*
1264 * If being flinged and user touches the screen, initiate drag;
1265 * otherwise don't. mScroller.isFinished should be false when
1266 * being flinged.
1267 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001268 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001269 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1270 if (finishedScrolling) {
1271 mTouchState = TOUCH_STATE_REST;
1272 mScroller.abortAnimation();
1273 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001274 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1275 mTouchState = TOUCH_STATE_SCROLLING;
1276 } else {
1277 mTouchState = TOUCH_STATE_REST;
1278 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001279 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001280
Winson Chung86f77532010-08-24 11:08:22 -07001281 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001282 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001283 if (!DISABLE_TOUCH_SIDE_PAGES) {
1284 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1285 if (getChildCount() > 0) {
1286 if (hitsPreviousPage(x, y)) {
1287 mTouchState = TOUCH_STATE_PREV_PAGE;
1288 } else if (hitsNextPage(x, y)) {
1289 mTouchState = TOUCH_STATE_NEXT_PAGE;
1290 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001291 }
1292 }
1293 }
1294 break;
1295 }
1296
Winson Chung321e9ee2010-08-09 13:37:56 -07001297 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001298 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001299 resetTouchState();
1300 // Just intercept the touch event on up if we tap outside the strict viewport
1301 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1302 return true;
1303 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001304 break;
1305
1306 case MotionEvent.ACTION_POINTER_UP:
1307 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001308 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001309 break;
1310 }
1311
1312 /*
1313 * The only time we want to intercept motion events is if we are in the
1314 * drag mode.
1315 */
1316 return mTouchState != TOUCH_STATE_REST;
1317 }
1318
Adam Cohenf8d28232011-02-01 21:47:00 -08001319 protected void determineScrollingStart(MotionEvent ev) {
1320 determineScrollingStart(ev, 1.0f);
1321 }
1322
Winson Chung321e9ee2010-08-09 13:37:56 -07001323 /*
1324 * Determines if we should change the touch state to start scrolling after the
1325 * user moves their touch point too far.
1326 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001327 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001328 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001329 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001330 if (pointerIndex == -1) return;
1331
1332 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001333 final float x = ev.getX(pointerIndex);
1334 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001335 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1336
1337 // If we're only allowing edge swipes, we break out early if the down event wasn't
1338 // at the edge.
1339 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1340
Winson Chung321e9ee2010-08-09 13:37:56 -07001341 final int xDiff = (int) Math.abs(x - mLastMotionX);
1342 final int yDiff = (int) Math.abs(y - mLastMotionY);
1343
Adam Cohenf8d28232011-02-01 21:47:00 -08001344 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001345 boolean xPaged = xDiff > mPagingTouchSlop;
1346 boolean xMoved = xDiff > touchSlop;
1347 boolean yMoved = yDiff > touchSlop;
1348
Adam Cohenf8d28232011-02-01 21:47:00 -08001349 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001350 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001351 // Scroll if the user moved far enough along the X axis
1352 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001353 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001354 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001355 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001356 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001357 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1358 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001359 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001360 }
1361 }
1362
Adam Cohen7d30a372013-07-01 17:03:59 -07001363 protected float getMaxScrollProgress() {
1364 return 1.0f;
1365 }
1366
Adam Cohenf8d28232011-02-01 21:47:00 -08001367 protected void cancelCurrentPageLongPress() {
1368 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001369 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001370 // Try canceling the long press. It could also have been scheduled
1371 // by a distant descendant, so use the mAllowLongPress flag to block
1372 // everything
1373 final View currentPage = getPageAt(mCurrentPage);
1374 if (currentPage != null) {
1375 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001376 }
1377 }
1378 }
1379
Adam Cohen7d30a372013-07-01 17:03:59 -07001380 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1381 final int halfScreenSize = getViewportWidth() / 2;
1382
1383 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1384 screenCenter = Math.max(halfScreenSize, screenCenter);
1385
1386 return getScrollProgress(screenCenter, v, page);
1387 }
1388
Adam Cohenb5ba0972011-09-07 18:02:31 -07001389 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001390 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001391
Adam Cohen96d30a12013-07-16 18:13:21 -07001392 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001393 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001394
1395 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001396 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1397 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001398 return scrollProgress;
1399 }
1400
Adam Cohenedb40762013-07-18 16:45:45 -07001401 public int getScrollForPage(int index) {
1402 if (mPageScrolls == null || index >= mPageScrolls.length) {
1403 return 0;
1404 } else {
1405 return mPageScrolls[index];
1406 }
1407 }
1408
Adam Cohene0f66b52010-11-23 15:06:07 -08001409 // This curve determines how the effect of scrolling over the limits of the page dimishes
1410 // as the user pulls further and further from the bounds
1411 private float overScrollInfluenceCurve(float f) {
1412 f -= 1.0f;
1413 return f * f * f + 1.0f;
1414 }
1415
Adam Cohenb5ba0972011-09-07 18:02:31 -07001416 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001417 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001418
1419 // We want to reach the max over scroll effect when the user has
1420 // over scrolled half the size of the screen
1421 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1422
1423 if (f == 0) return;
1424
1425 // Clamp this factor, f, to -1 < f < 1
1426 if (Math.abs(f) >= 1) {
1427 f /= Math.abs(f);
1428 }
1429
1430 int overScrollAmount = (int) Math.round(f * screenSize);
1431 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001432 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001433 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001434 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001435 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001436 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001437 }
1438 invalidate();
1439 }
1440
1441 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001442 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001443
1444 float f = (amount / screenSize);
1445
1446 if (f == 0) return;
1447 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1448
Adam Cohen7bfc9792011-01-28 13:52:37 -08001449 // Clamp this factor, f, to -1 < f < 1
1450 if (Math.abs(f) >= 1) {
1451 f /= Math.abs(f);
1452 }
1453
Adam Cohene0f66b52010-11-23 15:06:07 -08001454 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001455 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001456 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001457 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001458 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001459 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001460 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001461 }
1462 invalidate();
1463 }
1464
Adam Cohenb5ba0972011-09-07 18:02:31 -07001465 protected void overScroll(float amount) {
1466 dampedOverScroll(amount);
1467 }
1468
Michael Jurkac5b262c2011-01-12 20:24:50 -08001469 protected float maxOverScroll() {
1470 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001471 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001472 float f = 1.0f;
1473 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1474 return OVERSCROLL_DAMP_FACTOR * f;
1475 }
1476
Winson Chung321e9ee2010-08-09 13:37:56 -07001477 @Override
1478 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001479 if (DISABLE_TOUCH_INTERACTION) {
1480 return false;
1481 }
1482
Winson Chung45e1d6e2010-11-09 17:19:49 -08001483 // Skip touch handling if there are no pages to swipe
1484 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1485
Michael Jurkab8f06722010-10-10 15:58:46 -07001486 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001487
1488 final int action = ev.getAction();
1489
1490 switch (action & MotionEvent.ACTION_MASK) {
1491 case MotionEvent.ACTION_DOWN:
1492 /*
1493 * If being flinged and user touches, stop the fling. isFinished
1494 * will be false if being flinged.
1495 */
1496 if (!mScroller.isFinished()) {
1497 mScroller.abortAnimation();
1498 }
1499
1500 // Remember where the motion event started
1501 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001502 mDownMotionY = mLastMotionY = ev.getY();
1503 mDownScrollX = getScrollX();
1504 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1505 mParentDownMotionX = p[0];
1506 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001507 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001508 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001509 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001510
1511 // Determine if the down event is within the threshold to be an edge swipe
1512 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1513 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1514 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1515 mDownEventOnEdge = true;
1516 }
1517
Michael Jurka0142d492010-08-25 17:46:15 -07001518 if (mTouchState == TOUCH_STATE_SCROLLING) {
1519 pageBeginMoving();
1520 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001521 break;
1522
1523 case MotionEvent.ACTION_MOVE:
1524 if (mTouchState == TOUCH_STATE_SCROLLING) {
1525 // Scroll to follow the motion event
1526 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001527
1528 if (pointerIndex == -1) return true;
1529
Winson Chung321e9ee2010-08-09 13:37:56 -07001530 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001531 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001532
Adam Cohenaefd4e12011-02-14 16:39:38 -08001533 mTotalMotionX += Math.abs(deltaX);
1534
Winson Chungc0844aa2011-02-02 15:25:58 -08001535 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1536 // keep the remainder because we are actually testing if we've moved from the last
1537 // scrolled position (which is discrete).
1538 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001539 mTouchX += deltaX;
1540 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1541 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001542 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001543 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001544 } else {
1545 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001546 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001547 mLastMotionX = x;
1548 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001549 } else {
1550 awakenScrollBars();
1551 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001552 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1553 // Update the last motion position
1554 mLastMotionX = ev.getX();
1555 mLastMotionY = ev.getY();
1556
1557 // Update the parent down so that our zoom animations take this new movement into
1558 // account
1559 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1560 mParentDownMotionX = pt[0];
1561 mParentDownMotionY = pt[1];
1562 updateDragViewTranslationDuringDrag();
1563
1564 // Find the closest page to the touch point
1565 final int dragViewIndex = indexOfChild(mDragView);
1566 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1567 getViewportWidth());
1568 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1569 + bufferSize);
1570 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1571 - bufferSize);
1572
1573 // Change the drag view if we are hovering over the drop target
1574 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1575 (int) mParentDownMotionX, (int) mParentDownMotionY);
1576 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1577
1578 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1579 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1580 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1581 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1582 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1583 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1584
1585 float parentX = mParentDownMotionX;
1586 int pageIndexToSnapTo = -1;
1587 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1588 pageIndexToSnapTo = dragViewIndex - 1;
1589 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1590 pageIndexToSnapTo = dragViewIndex + 1;
1591 }
1592
1593 final int pageUnderPointIndex = pageIndexToSnapTo;
1594 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1595 mTempVisiblePagesRange[0] = 0;
1596 mTempVisiblePagesRange[1] = getPageCount() - 1;
1597 boundByReorderablePages(true, mTempVisiblePagesRange);
1598 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1599 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1600 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1601 mSidePageHoverIndex = pageUnderPointIndex;
1602 mSidePageHoverRunnable = new Runnable() {
1603 @Override
1604 public void run() {
1605 // Update the down scroll position to account for the fact that the
1606 // current page is moved
Adam Cohenedb40762013-07-18 16:45:45 -07001607 mDownScrollX = getScrollForPage(pageUnderPointIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001608
1609 // Setup the scroll to the correct page before we swap the views
1610 snapToPage(pageUnderPointIndex);
1611
1612 // For each of the pages between the paged view and the drag view,
1613 // animate them from the previous position to the new position in
1614 // the layout (as a result of the drag view moving in the layout)
1615 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1616 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1617 dragViewIndex + 1 : pageUnderPointIndex;
1618 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1619 dragViewIndex - 1 : pageUnderPointIndex;
1620 for (int i = lowerIndex; i <= upperIndex; ++i) {
1621 View v = getChildAt(i);
1622 // dragViewIndex < pageUnderPointIndex, so after we remove the
1623 // drag view all subsequent views to pageUnderPointIndex will
1624 // shift down.
1625 int oldX = getViewportOffsetX() + getChildOffset(i);
1626 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1627
1628 // Animate the view translation from its old position to its new
1629 // position
1630 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1631 if (anim != null) {
1632 anim.cancel();
1633 }
1634
1635 v.setTranslationX(oldX - newX);
1636 anim = new AnimatorSet();
1637 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1638 anim.playTogether(
1639 ObjectAnimator.ofFloat(v, "translationX", 0f));
1640 anim.start();
1641 v.setTag(anim);
1642 }
1643
1644 removeView(mDragView);
1645 onRemoveView(mDragView, false);
1646 addView(mDragView, pageUnderPointIndex);
1647 onAddView(mDragView, pageUnderPointIndex);
1648 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001649 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001650 }
1651 };
1652 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1653 }
1654 } else {
1655 removeCallbacks(mSidePageHoverRunnable);
1656 mSidePageHoverIndex = -1;
1657 }
Adam Cohen564976a2010-10-13 18:52:07 -07001658 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001659 determineScrollingStart(ev);
1660 }
1661 break;
1662
1663 case MotionEvent.ACTION_UP:
1664 if (mTouchState == TOUCH_STATE_SCROLLING) {
1665 final int activePointerId = mActivePointerId;
1666 final int pointerIndex = ev.findPointerIndex(activePointerId);
1667 final float x = ev.getX(pointerIndex);
1668 final VelocityTracker velocityTracker = mVelocityTracker;
1669 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1670 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001671 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001672 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001673 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1674 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001675
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001676 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1677
Adam Cohen00481b32011-11-18 12:03:48 -08001678 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001679 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001680
Adam Cohenaefd4e12011-02-14 16:39:38 -08001681 // In the case that the page is moved far to one direction and then is flung
1682 // in the opposite direction, we use a threshold to determine whether we should
1683 // just return to the starting page, or if we should skip one further.
1684 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001685 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001686 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001687 returnToOriginalPage = true;
1688 }
1689
Adam Cohenaefd4e12011-02-14 16:39:38 -08001690 int finalPage;
1691 // We give flings precedence over large moves, which is why we short-circuit our
1692 // test for a large move if a fling has been registered. That is, a large
1693 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001694 final boolean isRtl = isLayoutRtl();
1695 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1696 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1697 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1698 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001699 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1700 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001701 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1702 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001703 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001704 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1705 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001706 } else {
1707 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001708 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001709 // at this point we have not moved beyond the touch slop
1710 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1711 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001712 int nextPage = Math.max(0, mCurrentPage - 1);
1713 if (nextPage != mCurrentPage) {
1714 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001715 } else {
1716 snapToDestination();
1717 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001718 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001719 // at this point we have not moved beyond the touch slop
1720 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1721 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001722 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1723 if (nextPage != mCurrentPage) {
1724 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001725 } else {
1726 snapToDestination();
1727 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001728 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1729 // Update the last motion position
1730 mLastMotionX = ev.getX();
1731 mLastMotionY = ev.getY();
1732
1733 // Update the parent down so that our zoom animations take this new movement into
1734 // account
1735 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1736 mParentDownMotionX = pt[0];
1737 mParentDownMotionY = pt[1];
1738 updateDragViewTranslationDuringDrag();
1739 boolean handledFling = false;
1740 if (!DISABLE_FLING_TO_DELETE) {
1741 // Check the velocity and see if we are flinging-to-delete
1742 PointF flingToDeleteVector = isFlingingToDelete();
1743 if (flingToDeleteVector != null) {
1744 onFlingToDelete(flingToDeleteVector);
1745 handledFling = true;
1746 }
1747 }
1748 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1749 (int) mParentDownMotionY)) {
1750 onDropToDelete();
1751 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001752 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001753 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001754 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001755
1756 // Remove the callback to wait for the side page hover timeout
1757 removeCallbacks(mSidePageHoverRunnable);
1758 // End any intermediate reordering states
1759 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001760 break;
1761
1762 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001763 if (mTouchState == TOUCH_STATE_SCROLLING) {
1764 snapToDestination();
1765 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001766 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001767 break;
1768
1769 case MotionEvent.ACTION_POINTER_UP:
1770 onSecondaryPointerUp(ev);
1771 break;
1772 }
1773
1774 return true;
1775 }
1776
Adam Cohen7d30a372013-07-01 17:03:59 -07001777 public void onFlingToDelete(View v) {}
1778 public void onRemoveView(View v, boolean deletePermanently) {}
1779 public void onRemoveViewAnimationCompleted() {}
1780 public void onAddView(View v, int index) {}
1781
1782 private void resetTouchState() {
1783 releaseVelocityTracker();
1784 endReordering();
1785 mTouchState = TOUCH_STATE_REST;
1786 mActivePointerId = INVALID_POINTER;
1787 mDownEventOnEdge = false;
1788 }
1789
1790 protected void onUnhandledTap(MotionEvent ev) {}
1791
Winson Chung185d7162011-02-28 13:47:29 -08001792 @Override
1793 public boolean onGenericMotionEvent(MotionEvent event) {
1794 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1795 switch (event.getAction()) {
1796 case MotionEvent.ACTION_SCROLL: {
1797 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1798 final float vscroll;
1799 final float hscroll;
1800 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1801 vscroll = 0;
1802 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1803 } else {
1804 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1805 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1806 }
1807 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001808 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1809 : (hscroll > 0 || vscroll > 0);
1810 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001811 scrollRight();
1812 } else {
1813 scrollLeft();
1814 }
1815 return true;
1816 }
1817 }
1818 }
1819 }
1820 return super.onGenericMotionEvent(event);
1821 }
1822
Michael Jurkab8f06722010-10-10 15:58:46 -07001823 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1824 if (mVelocityTracker == null) {
1825 mVelocityTracker = VelocityTracker.obtain();
1826 }
1827 mVelocityTracker.addMovement(ev);
1828 }
1829
1830 private void releaseVelocityTracker() {
1831 if (mVelocityTracker != null) {
1832 mVelocityTracker.recycle();
1833 mVelocityTracker = null;
1834 }
1835 }
1836
Winson Chung321e9ee2010-08-09 13:37:56 -07001837 private void onSecondaryPointerUp(MotionEvent ev) {
1838 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1839 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1840 final int pointerId = ev.getPointerId(pointerIndex);
1841 if (pointerId == mActivePointerId) {
1842 // This was our active pointer going up. Choose a new
1843 // active pointer and adjust accordingly.
1844 // TODO: Make this decision more intelligent.
1845 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1846 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1847 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001848 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001849 mActivePointerId = ev.getPointerId(newPointerIndex);
1850 if (mVelocityTracker != null) {
1851 mVelocityTracker.clear();
1852 }
1853 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001854 }
1855
Winson Chung321e9ee2010-08-09 13:37:56 -07001856 @Override
1857 public void requestChildFocus(View child, View focused) {
1858 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001859 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001860 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001861 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001862 }
1863 }
1864
Winson Chung1908d072011-02-24 18:09:44 -08001865 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001866 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001867 }
1868
Adam Cohen7d30a372013-07-01 17:03:59 -07001869 int getPageNearestToPoint(float x) {
1870 int index = 0;
1871 for (int i = 0; i < getChildCount(); ++i) {
1872 if (x < getChildAt(i).getRight() - getScrollX()) {
1873 return index;
1874 } else {
1875 index++;
1876 }
1877 }
1878 return Math.min(index, getChildCount() - 1);
1879 }
1880
Adam Cohend19d3ca2010-09-15 14:43:42 -07001881 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001882 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001883 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001884 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001885 final int childCount = getChildCount();
1886 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001887 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001888 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001889 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001890 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001891 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1892 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1893 minDistanceFromScreenCenter = distanceFromScreenCenter;
1894 minDistanceFromScreenCenterIndex = i;
1895 }
1896 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001897 return minDistanceFromScreenCenterIndex;
1898 }
1899
1900 protected void snapToDestination() {
1901 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001902 }
1903
Adam Cohene0f66b52010-11-23 15:06:07 -08001904 private static class ScrollInterpolator implements Interpolator {
1905 public ScrollInterpolator() {
1906 }
1907
1908 public float getInterpolation(float t) {
1909 t -= 1.0f;
1910 return t*t*t*t*t + 1;
1911 }
1912 }
1913
1914 // We want the duration of the page snap animation to be influenced by the distance that
1915 // the screen has to travel, however, we don't want this duration to be effected in a
1916 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1917 // of travel has on the overall snap duration.
1918 float distanceInfluenceForSnapDuration(float f) {
1919 f -= 0.5f; // center the values about 0.
1920 f *= 0.3f * Math.PI / 2.0f;
1921 return (float) Math.sin(f);
1922 }
1923
Michael Jurka0142d492010-08-25 17:46:15 -07001924 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001925 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001926 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001927
Adam Cohenedb40762013-07-18 16:45:45 -07001928 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08001929 int delta = newX - mUnboundedScrollX;
1930 int duration = 0;
1931
Adam Cohen265b9a62011-12-07 14:37:18 -08001932 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001933 // If the velocity is low enough, then treat this more as an automatic page advance
1934 // as opposed to an apparent physical response to flinging
1935 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1936 return;
1937 }
1938
1939 // Here we compute a "distance" that will be used in the computation of the overall
1940 // snap duration. This is a function of the actual distance that needs to be traveled;
1941 // we keep this value close to half screen size in order to reduce the variance in snap
1942 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001943 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001944 float distance = halfScreenSize + halfScreenSize *
1945 distanceInfluenceForSnapDuration(distanceRatio);
1946
1947 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001948 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001949
1950 // we want the page's snap velocity to approximately match the velocity at which the
1951 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001952 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1953 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001954
1955 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001956 }
1957
1958 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001959 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001960 }
1961
Adam Cohen7d30a372013-07-01 17:03:59 -07001962 protected void snapToPageImmediately(int whichPage) {
1963 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1964 }
1965
Michael Jurka0142d492010-08-25 17:46:15 -07001966 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001967 snapToPage(whichPage, duration, false);
1968 }
1969
1970 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07001971 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07001972
Adam Cohenedb40762013-07-18 16:45:45 -07001973 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08001974 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001975 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07001976 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07001977 }
1978
1979 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001980 snapToPage(whichPage, delta, duration, false);
1981 }
Michael Jurka0142d492010-08-25 17:46:15 -07001982
Adam Cohen7d30a372013-07-01 17:03:59 -07001983 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
1984 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07001985 View focusedChild = getFocusedChild();
1986 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07001987 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07001988 focusedChild.clearFocus();
1989 }
1990
1991 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001992 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07001993 if (immediate) {
1994 duration = 0;
1995 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001996 duration = Math.abs(delta);
1997 }
1998
1999 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002000 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002001
Michael Jurka0142d492010-08-25 17:46:15 -07002002 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002003
2004 // Trigger a compute() to finish switching pages if necessary
2005 if (immediate) {
2006 computeScroll();
2007 }
2008
2009 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002010 invalidate();
2011 }
2012
Winson Chung321e9ee2010-08-09 13:37:56 -07002013 public void scrollLeft() {
2014 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002015 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002016 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002017 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002018 }
2019 }
2020
2021 public void scrollRight() {
2022 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002023 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002024 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002025 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002026 }
2027 }
2028
Winson Chung86f77532010-08-24 11:08:22 -07002029 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002030 int result = -1;
2031 if (v != null) {
2032 ViewParent vp = v.getParent();
2033 int count = getChildCount();
2034 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002035 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002036 return i;
2037 }
2038 }
2039 }
2040 return result;
2041 }
2042
2043 /**
2044 * @return True is long presses are still allowed for the current touch
2045 */
2046 public boolean allowLongPress() {
2047 return mAllowLongPress;
2048 }
2049
Michael Jurka0142d492010-08-25 17:46:15 -07002050 /**
2051 * Set true to allow long-press events to be triggered, usually checked by
2052 * {@link Launcher} to accept or block dpad-initiated long-presses.
2053 */
2054 public void setAllowLongPress(boolean allowLongPress) {
2055 mAllowLongPress = allowLongPress;
2056 }
2057
Winson Chung321e9ee2010-08-09 13:37:56 -07002058 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002059 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002060
2061 SavedState(Parcelable superState) {
2062 super(superState);
2063 }
2064
2065 private SavedState(Parcel in) {
2066 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002067 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002068 }
2069
2070 @Override
2071 public void writeToParcel(Parcel out, int flags) {
2072 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002073 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002074 }
2075
2076 public static final Parcelable.Creator<SavedState> CREATOR =
2077 new Parcelable.Creator<SavedState>() {
2078 public SavedState createFromParcel(Parcel in) {
2079 return new SavedState(in);
2080 }
2081
2082 public SavedState[] newArray(int size) {
2083 return new SavedState[size];
2084 }
2085 };
2086 }
2087
Winson Chungf314b0e2011-08-16 11:54:27 -07002088 protected void loadAssociatedPages(int page) {
2089 loadAssociatedPages(page, false);
2090 }
2091 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002092 if (mContentIsRefreshable) {
2093 final int count = getChildCount();
2094 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002095 int lowerPageBound = getAssociatedLowerPageBound(page);
2096 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002097 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2098 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002099 // First, clear any pages that should no longer be loaded
2100 for (int i = 0; i < count; ++i) {
2101 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002102 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002103 if (layout.getPageChildCount() > 0) {
2104 layout.removeAllViewsOnPage();
2105 }
2106 mDirtyPageContent.set(i, true);
2107 }
2108 }
2109 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002110 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002111 if ((i != page) && immediateAndOnly) {
2112 continue;
2113 }
Michael Jurka0142d492010-08-25 17:46:15 -07002114 if (lowerPageBound <= i && i <= upperPageBound) {
2115 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002116 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002117 mDirtyPageContent.set(i, false);
2118 }
Winson Chung86f77532010-08-24 11:08:22 -07002119 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002120 }
2121 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002122 }
2123 }
2124
Winson Chunge3193b92010-09-10 11:44:42 -07002125 protected int getAssociatedLowerPageBound(int page) {
2126 return Math.max(0, page - 1);
2127 }
2128 protected int getAssociatedUpperPageBound(int page) {
2129 final int count = getChildCount();
2130 return Math.min(page + 1, count - 1);
2131 }
2132
Winson Chung86f77532010-08-24 11:08:22 -07002133 /**
2134 * This method is called ONLY to synchronize the number of pages that the paged view has.
2135 * To actually fill the pages with information, implement syncPageItems() below. It is
2136 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2137 * and therefore, individual page items do not need to be updated in this method.
2138 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002139 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002140
2141 /**
2142 * This method is called to synchronize the items that are on a particular page. If views on
2143 * the page can be reused, then they should be updated within this method.
2144 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002145 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002146
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002147 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002148 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002149 }
2150 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002151 invalidatePageData(currentPage, false);
2152 }
2153 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002154 if (!mIsDataReady) {
2155 return;
2156 }
2157
Michael Jurka0142d492010-08-25 17:46:15 -07002158 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002159 // Force all scrolling-related behavior to end
2160 mScroller.forceFinished(true);
2161 mNextPage = INVALID_PAGE;
2162
Michael Jurka0142d492010-08-25 17:46:15 -07002163 // Update all the pages
2164 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002165
Winson Chung5a808352011-06-27 19:08:49 -07002166 // We must force a measure after we've loaded the pages to update the content width and
2167 // to determine the full scroll width
2168 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2169 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2170
2171 // Set a new page as the current page if necessary
2172 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002173 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002174 }
2175
Michael Jurka0142d492010-08-25 17:46:15 -07002176 // Mark each of the pages as dirty
2177 final int count = getChildCount();
2178 mDirtyPageContent.clear();
2179 for (int i = 0; i < count; ++i) {
2180 mDirtyPageContent.add(true);
2181 }
2182
2183 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002184 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002185 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002186 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002187 }
Winson Chung007c6982011-06-14 13:27:53 -07002188
Adam Cohen7d30a372013-07-01 17:03:59 -07002189 // Animate the drag view back to the original position
2190 void animateDragViewToOriginalPosition() {
2191 if (mDragView != null) {
2192 AnimatorSet anim = new AnimatorSet();
2193 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2194 anim.playTogether(
2195 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2196 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2197 anim.addListener(new AnimatorListenerAdapter() {
2198 @Override
2199 public void onAnimationEnd(Animator animation) {
2200 onPostReorderingAnimationCompleted();
2201 }
2202 });
2203 anim.start();
2204 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002205 }
2206
Adam Cohen7d30a372013-07-01 17:03:59 -07002207 // "Zooms out" the PagedView to reveal more side pages
2208 protected boolean zoomOut() {
2209 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2210 mZoomInOutAnim.cancel();
2211 }
2212
2213 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2214 mZoomInOutAnim = new AnimatorSet();
2215 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2216 mZoomInOutAnim.playTogether(
2217 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2218 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2219 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2220 @Override
2221 public void onAnimationStart(Animator animation) {
2222 // Show the delete drop target
2223 if (mDeleteDropTarget != null) {
2224 mDeleteDropTarget.setVisibility(View.VISIBLE);
2225 mDeleteDropTarget.animate().alpha(1f)
2226 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2227 .setListener(new AnimatorListenerAdapter() {
2228 @Override
2229 public void onAnimationStart(Animator animation) {
2230 mDeleteDropTarget.setAlpha(0f);
2231 }
2232 });
2233 }
2234 }
2235 });
2236 mZoomInOutAnim.start();
2237 return true;
2238 }
2239 return false;
2240 }
2241
2242 protected void onStartReordering() {
2243 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2244 mTouchState = TOUCH_STATE_REORDERING;
2245 mIsReordering = true;
2246
2247 // Mark all the non-widget pages as invisible
2248 getVisiblePages(mTempVisiblePagesRange);
2249 boundByReorderablePages(true, mTempVisiblePagesRange);
2250 for (int i = 0; i < getPageCount(); ++i) {
2251 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2252 getPageAt(i).setAlpha(0f);
2253 }
2254 }
2255
2256 // We must invalidate to trigger a redraw to update the layers such that the drag view
2257 // is always drawn on top
2258 invalidate();
2259 }
2260
2261 private void onPostReorderingAnimationCompleted() {
2262 // Trigger the callback when reordering has settled
2263 --mPostReorderingPreZoomInRemainingAnimationCount;
2264 if (mPostReorderingPreZoomInRunnable != null &&
2265 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2266 mPostReorderingPreZoomInRunnable.run();
2267 mPostReorderingPreZoomInRunnable = null;
2268 }
2269 }
2270
2271 protected void onEndReordering() {
2272 mIsReordering = false;
2273
2274 // Mark all the non-widget pages as visible again
2275 getVisiblePages(mTempVisiblePagesRange);
2276 boundByReorderablePages(true, mTempVisiblePagesRange);
2277 for (int i = 0; i < getPageCount(); ++i) {
2278 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2279 getPageAt(i).setAlpha(1f);
2280 }
2281 }
2282 }
2283
2284 public boolean startReordering() {
2285 int dragViewIndex = getPageNearestToCenterOfScreen();
2286 mTempVisiblePagesRange[0] = 0;
2287 mTempVisiblePagesRange[1] = getPageCount() - 1;
2288 boundByReorderablePages(true, mTempVisiblePagesRange);
2289 mReorderingStarted = true;
2290
2291 // Check if we are within the reordering range
2292 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2293 dragViewIndex <= mTempVisiblePagesRange[1]) {
2294 if (zoomOut()) {
2295 // Find the drag view under the pointer
2296 mDragView = getChildAt(dragViewIndex);
2297
2298 onStartReordering();
2299 }
2300 return true;
2301 }
2302 return false;
2303 }
2304
2305 boolean isReordering(boolean testTouchState) {
2306 boolean state = mIsReordering;
2307 if (testTouchState) {
2308 state &= (mTouchState == TOUCH_STATE_REORDERING);
2309 }
2310 return state;
2311 }
2312 void endReordering() {
2313 // For simplicity, we call endReordering sometimes even if reordering was never started.
2314 // In that case, we don't want to do anything.
2315 if (!mReorderingStarted) return;
2316 mReorderingStarted = false;
2317
2318 // If we haven't flung-to-delete the current child, then we just animate the drag view
2319 // back into position
2320 final Runnable onCompleteRunnable = new Runnable() {
2321 @Override
2322 public void run() {
2323 onEndReordering();
2324 }
2325 };
2326 if (!mDeferringForDelete) {
2327 mPostReorderingPreZoomInRunnable = new Runnable() {
2328 public void run() {
2329 zoomIn(onCompleteRunnable);
2330 };
2331 };
2332
2333 mPostReorderingPreZoomInRemainingAnimationCount =
2334 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2335 // Snap to the current page
2336 snapToPage(indexOfChild(mDragView), 0);
2337 // Animate the drag view back to the front position
2338 animateDragViewToOriginalPosition();
2339 } else {
2340 // Handled in post-delete-animation-callbacks
2341 }
2342 }
2343
2344 // "Zooms in" the PagedView to highlight the current page
2345 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2346 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2347 mZoomInOutAnim.cancel();
2348 }
2349 if (getScaleX() < 1f || getScaleY() < 1f) {
2350 mZoomInOutAnim = new AnimatorSet();
2351 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2352 mZoomInOutAnim.playTogether(
2353 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2354 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2355 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2356 @Override
2357 public void onAnimationStart(Animator animation) {
2358 // Hide the delete drop target
2359 if (mDeleteDropTarget != null) {
2360 mDeleteDropTarget.animate().alpha(0f)
2361 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2362 .setListener(new AnimatorListenerAdapter() {
2363 @Override
2364 public void onAnimationEnd(Animator animation) {
2365 mDeleteDropTarget.setVisibility(View.GONE);
2366 }
2367 });
2368 }
2369 }
2370 @Override
2371 public void onAnimationCancel(Animator animation) {
2372 mDragView = null;
2373 }
2374 @Override
2375 public void onAnimationEnd(Animator animation) {
2376 mDragView = null;
2377 if (onCompleteRunnable != null) {
2378 onCompleteRunnable.run();
2379 }
2380 }
2381 });
2382 mZoomInOutAnim.start();
2383 return true;
2384 } else {
2385 if (onCompleteRunnable != null) {
2386 onCompleteRunnable.run();
2387 }
2388 }
2389 return false;
2390 }
2391
2392 /*
2393 * Flinging to delete - IN PROGRESS
2394 */
2395 private PointF isFlingingToDelete() {
2396 ViewConfiguration config = ViewConfiguration.get(getContext());
2397 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2398
2399 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2400 // Do a quick dot product test to ensure that we are flinging upwards
2401 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2402 mVelocityTracker.getYVelocity());
2403 PointF upVec = new PointF(0f, -1f);
2404 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2405 (vel.length() * upVec.length()));
2406 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2407 return vel;
2408 }
2409 }
2410 return null;
2411 }
2412
2413 /**
2414 * Creates an animation from the current drag view along its current velocity vector.
2415 * For this animation, the alpha runs for a fixed duration and we update the position
2416 * progressively.
2417 */
2418 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2419 private View mDragView;
2420 private PointF mVelocity;
2421 private Rect mFrom;
2422 private long mPrevTime;
2423 private float mFriction;
2424
2425 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2426
2427 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2428 long startTime, float friction) {
2429 mDragView = dragView;
2430 mVelocity = vel;
2431 mFrom = from;
2432 mPrevTime = startTime;
2433 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2434 }
2435
2436 @Override
2437 public void onAnimationUpdate(ValueAnimator animation) {
2438 float t = ((Float) animation.getAnimatedValue()).floatValue();
2439 long curTime = AnimationUtils.currentAnimationTimeMillis();
2440
2441 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2442 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2443
2444 mDragView.setTranslationX(mFrom.left);
2445 mDragView.setTranslationY(mFrom.top);
2446 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2447
2448 mVelocity.x *= mFriction;
2449 mVelocity.y *= mFriction;
2450 mPrevTime = curTime;
2451 }
2452 };
2453
2454 private static final int ANIM_TAG_KEY = 100;
2455
2456 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2457 return new Runnable() {
2458 @Override
2459 public void run() {
2460 int dragViewIndex = indexOfChild(dragView);
2461
2462 // For each of the pages around the drag view, animate them from the previous
2463 // position to the new position in the layout (as a result of the drag view moving
2464 // in the layout)
2465 // NOTE: We can make an assumption here because we have side-bound pages that we
2466 // will always have pages to animate in from the left
2467 getVisiblePages(mTempVisiblePagesRange);
2468 boundByReorderablePages(true, mTempVisiblePagesRange);
2469 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2470 boolean slideFromLeft = (isLastWidgetPage ||
2471 dragViewIndex > mTempVisiblePagesRange[0]);
2472
2473 // Setup the scroll to the correct page before we swap the views
2474 if (slideFromLeft) {
2475 snapToPageImmediately(dragViewIndex - 1);
2476 }
2477
2478 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2479 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2480 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2481 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2482 ArrayList<Animator> animations = new ArrayList<Animator>();
2483 for (int i = lowerIndex; i <= upperIndex; ++i) {
2484 View v = getChildAt(i);
2485 // dragViewIndex < pageUnderPointIndex, so after we remove the
2486 // drag view all subsequent views to pageUnderPointIndex will
2487 // shift down.
2488 int oldX = 0;
2489 int newX = 0;
2490 if (slideFromLeft) {
2491 if (i == 0) {
2492 // Simulate the page being offscreen with the page spacing
2493 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2494 - mPageSpacing;
2495 } else {
2496 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2497 }
2498 newX = getViewportOffsetX() + getChildOffset(i);
2499 } else {
2500 oldX = getChildOffset(i) - getChildOffset(i - 1);
2501 newX = 0;
2502 }
2503
2504 // Animate the view translation from its old position to its new
2505 // position
2506 AnimatorSet anim = (AnimatorSet) v.getTag();
2507 if (anim != null) {
2508 anim.cancel();
2509 }
2510
2511 // Note: Hacky, but we want to skip any optimizations to not draw completely
2512 // hidden views
2513 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2514 v.setTranslationX(oldX - newX);
2515 anim = new AnimatorSet();
2516 anim.playTogether(
2517 ObjectAnimator.ofFloat(v, "translationX", 0f),
2518 ObjectAnimator.ofFloat(v, "alpha", 1f));
2519 animations.add(anim);
2520 v.setTag(ANIM_TAG_KEY, anim);
2521 }
2522
2523 AnimatorSet slideAnimations = new AnimatorSet();
2524 slideAnimations.playTogether(animations);
2525 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2526 slideAnimations.addListener(new AnimatorListenerAdapter() {
2527 @Override
2528 public void onAnimationEnd(Animator animation) {
2529 final Runnable onCompleteRunnable = new Runnable() {
2530 @Override
2531 public void run() {
2532 mDeferringForDelete = false;
2533 onEndReordering();
2534 onRemoveViewAnimationCompleted();
2535 }
2536 };
2537 zoomIn(onCompleteRunnable);
2538 }
2539 });
2540 slideAnimations.start();
2541
2542 removeView(dragView);
2543 onRemoveView(dragView, true);
2544 }
2545 };
2546 }
2547
2548 public void onFlingToDelete(PointF vel) {
2549 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2550
2551 // NOTE: Because it takes time for the first frame of animation to actually be
2552 // called and we expect the animation to be a continuation of the fling, we have
2553 // to account for the time that has elapsed since the fling finished. And since
2554 // we don't have a startDelay, we will always get call to update when we call
2555 // start() (which we want to ignore).
2556 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2557 private int mCount = -1;
2558 private long mStartTime;
2559 private float mOffset;
2560 /* Anonymous inner class ctor */ {
2561 mStartTime = startTime;
2562 }
2563
2564 @Override
2565 public float getInterpolation(float t) {
2566 if (mCount < 0) {
2567 mCount++;
2568 } else if (mCount == 0) {
2569 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2570 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2571 mCount++;
2572 }
2573 return Math.min(1f, mOffset + t);
2574 }
2575 };
2576
2577 final Rect from = new Rect();
2578 final View dragView = mDragView;
2579 from.left = (int) dragView.getTranslationX();
2580 from.top = (int) dragView.getTranslationY();
2581 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2582 from, startTime, FLING_TO_DELETE_FRICTION);
2583
2584 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2585
2586 // Create and start the animation
2587 ValueAnimator mDropAnim = new ValueAnimator();
2588 mDropAnim.setInterpolator(tInterpolator);
2589 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2590 mDropAnim.setFloatValues(0f, 1f);
2591 mDropAnim.addUpdateListener(updateCb);
2592 mDropAnim.addListener(new AnimatorListenerAdapter() {
2593 public void onAnimationEnd(Animator animation) {
2594 onAnimationEndRunnable.run();
2595 }
2596 });
2597 mDropAnim.start();
2598 mDeferringForDelete = true;
2599 }
2600
2601 /* Drag to delete */
2602 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2603 if (mDeleteDropTarget != null) {
2604 mAltTmpRect.set(0, 0, 0, 0);
2605 View parent = (View) mDeleteDropTarget.getParent();
2606 if (parent != null) {
2607 parent.getGlobalVisibleRect(mAltTmpRect);
2608 }
2609 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2610 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2611 return mTmpRect.contains(x, y);
2612 }
2613 return false;
2614 }
2615
2616 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2617
2618 private void onDropToDelete() {
2619 final View dragView = mDragView;
2620
2621 final float toScale = 0f;
2622 final float toAlpha = 0f;
2623
2624 // Create and start the complex animation
2625 ArrayList<Animator> animations = new ArrayList<Animator>();
2626 AnimatorSet motionAnim = new AnimatorSet();
2627 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2628 motionAnim.playTogether(
2629 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2630 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2631 animations.add(motionAnim);
2632
2633 AnimatorSet alphaAnim = new AnimatorSet();
2634 alphaAnim.setInterpolator(new LinearInterpolator());
2635 alphaAnim.playTogether(
2636 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2637 animations.add(alphaAnim);
2638
2639 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2640
2641 AnimatorSet anim = new AnimatorSet();
2642 anim.playTogether(animations);
2643 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2644 anim.addListener(new AnimatorListenerAdapter() {
2645 public void onAnimationEnd(Animator animation) {
2646 onAnimationEndRunnable.run();
2647 }
2648 });
2649 anim.start();
2650
2651 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002652 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002653
2654 /* Accessibility */
2655 @Override
2656 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2657 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002658 info.setScrollable(getPageCount() > 1);
2659 if (getCurrentPage() < getPageCount() - 1) {
2660 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2661 }
2662 if (getCurrentPage() > 0) {
2663 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2664 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002665 }
2666
2667 @Override
2668 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2669 super.onInitializeAccessibilityEvent(event);
2670 event.setScrollable(true);
2671 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2672 event.setFromIndex(mCurrentPage);
2673 event.setToIndex(mCurrentPage);
2674 event.setItemCount(getChildCount());
2675 }
2676 }
2677
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002678 @Override
2679 public boolean performAccessibilityAction(int action, Bundle arguments) {
2680 if (super.performAccessibilityAction(action, arguments)) {
2681 return true;
2682 }
2683 switch (action) {
2684 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2685 if (getCurrentPage() < getPageCount() - 1) {
2686 scrollRight();
2687 return true;
2688 }
2689 } break;
2690 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2691 if (getCurrentPage() > 0) {
2692 scrollLeft();
2693 return true;
2694 }
2695 } break;
2696 }
2697 return false;
2698 }
2699
Adam Cohen0ffac432013-07-10 11:19:26 -07002700 protected String getCurrentPageDescription() {
2701 return String.format(getContext().getString(R.string.default_scroll_format),
2702 getNextPage() + 1, getChildCount());
2703 }
2704
Winson Chungd11265e2011-08-30 13:37:23 -07002705 @Override
2706 public boolean onHoverEvent(android.view.MotionEvent event) {
2707 return true;
2708 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002709}