blob: aaff5888697bd05d9834947d030f7531d294af48 [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;
Winson Chung9c0565f2013-07-19 13:49:06 -0700184 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700185
Patrick Dubroy1262e362010-10-06 15:49:50 -0700186 protected boolean mIsPageMoving = false;
187
Winson Chungf0ea4d32011-06-06 14:27:16 -0700188 // All syncs and layout passes are deferred until data is ready.
189 protected boolean mIsDataReady = false;
190
Adam Cohen7d30a372013-07-01 17:03:59 -0700191 protected boolean mAllowLongPress = true;
192
Winson Chungd2be3812013-07-16 11:11:32 -0700193 // Page Indicator
194 private int mPageIndicatorViewId;
195 private PageIndicator mPageIndicator;
Winson Chung007c6982011-06-14 13:27:53 -0700196
Adam Cohen7d30a372013-07-01 17:03:59 -0700197 // The viewport whether the pages are to be contained (the actual view may be larger than the
198 // viewport)
199 private Rect mViewport = new Rect();
200
201 // Reordering
202 // We use the min scale to determine how much to expand the actually PagedView measured
203 // dimensions such that when we are zoomed out, the view is not clipped
204 private int REORDERING_DROP_REPOSITION_DURATION = 200;
205 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
206 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
207 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 300;
208 private float REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE = 0.1f;
209 private long REORDERING_DELETE_DROP_TARGET_FADE_DURATION = 150;
210 private float mMinScale = 1f;
211 protected View mDragView;
212 protected AnimatorSet mZoomInOutAnim;
213 private Runnable mSidePageHoverRunnable;
214 private int mSidePageHoverIndex = -1;
215 // This variable's scope is only for the duration of startReordering() and endReordering()
216 private boolean mReorderingStarted = false;
217 // This variable's scope is for the duration of startReordering() and after the zoomIn()
218 // animation after endReordering()
219 private boolean mIsReordering;
220 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
221 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
222 private int mPostReorderingPreZoomInRemainingAnimationCount;
223 private Runnable mPostReorderingPreZoomInRunnable;
224
225 // Edge swiping
226 private boolean mOnlyAllowEdgeSwipes = false;
227 private boolean mDownEventOnEdge = false;
228 private int mEdgeSwipeRegionSize = 0;
229
230 // Convenience/caching
231 private Matrix mTmpInvMatrix = new Matrix();
232 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700233 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700234 private Rect mTmpRect = new Rect();
235 private Rect mAltTmpRect = new Rect();
236
237 // Fling to delete
238 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
239 private float FLING_TO_DELETE_FRICTION = 0.035f;
240 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
241 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
242 protected int mFlingToDeleteThresholdVelocity = -1400;
243 // Drag to delete
244 private boolean mDeferringForDelete = false;
245 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
246 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
247
248 // Drop to delete
249 private View mDeleteDropTarget;
250
251 private boolean mAutoComputePageSpacing = false;
252 private boolean mRecomputePageSpacing = false;
253
254 // Bouncer
255 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700256
Winson Chung86f77532010-08-24 11:08:22 -0700257 public interface PageSwitchListener {
258 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700259 }
260
Winson Chung321e9ee2010-08-09 13:37:56 -0700261 public PagedView(Context context) {
262 this(context, null);
263 }
264
265 public PagedView(Context context, AttributeSet attrs) {
266 this(context, attrs, 0);
267 }
268
269 public PagedView(Context context, AttributeSet attrs, int defStyle) {
270 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700271
Adam Cohen9c4949e2010-10-05 12:27:22 -0700272 TypedArray a = context.obtainStyledAttributes(attrs,
273 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800274 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700275 if (mPageSpacing < 0) {
276 mAutoComputePageSpacing = mRecomputePageSpacing = true;
277 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700278 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800279 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700280 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800281 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700282 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800283 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700284 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800285 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700286 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700287 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700288 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700289 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700290 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700291 a.recycle();
292
Winson Chung321e9ee2010-08-09 13:37:56 -0700293 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700294 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700295 }
296
297 /**
298 * Initializes various states for this workspace.
299 */
Michael Jurka0142d492010-08-25 17:46:15 -0700300 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700301 mDirtyPageContent = new ArrayList<Boolean>();
302 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800303 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700304 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700305 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700306
307 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700308 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700309 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
310 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700311 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800312
Adam Cohen7d30a372013-07-01 17:03:59 -0700313 // Scale the fling-to-delete threshold by the density
314 mFlingToDeleteThresholdVelocity =
315 (int) (mFlingToDeleteThresholdVelocity * mDensity);
316
Adam Cohen265b9a62011-12-07 14:37:18 -0800317 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
318 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
319 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700320 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700321 }
322
Winson Chungd2be3812013-07-16 11:11:32 -0700323 protected void onAttachedToWindow() {
324 // Hook up the page indicator
325 ViewGroup parent = (ViewGroup) getParent();
326 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
327 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
328 mPageIndicator.removeAllMarkers();
329 mPageIndicator.addMarkers(getChildCount());
330 }
331 }
332
333 protected void onDetachedFromWindow() {
334 // Unhook the page indicator
335 mPageIndicator = null;
336 }
337
Adam Cohen7d30a372013-07-01 17:03:59 -0700338 void setDeleteDropTarget(View v) {
339 mDeleteDropTarget = v;
340 }
341
342 // Convenience methods to map points from self to parent and vice versa
343 float[] mapPointFromViewToParent(View v, float x, float y) {
344 mTmpPoint[0] = x;
345 mTmpPoint[1] = y;
346 v.getMatrix().mapPoints(mTmpPoint);
347 mTmpPoint[0] += v.getLeft();
348 mTmpPoint[1] += v.getTop();
349 return mTmpPoint;
350 }
351 float[] mapPointFromParentToView(View v, float x, float y) {
352 mTmpPoint[0] = x - v.getLeft();
353 mTmpPoint[1] = y - v.getTop();
354 v.getMatrix().invert(mTmpInvMatrix);
355 mTmpInvMatrix.mapPoints(mTmpPoint);
356 return mTmpPoint;
357 }
358
359 void updateDragViewTranslationDuringDrag() {
360 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
361 float y = mLastMotionY - mDownMotionY;
362 mDragView.setTranslationX(x);
363 mDragView.setTranslationY(y);
364
365 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
366 }
367
368 public void setMinScale(float f) {
369 mMinScale = f;
370 requestLayout();
371 }
372
373 @Override
374 public void setScaleX(float scaleX) {
375 super.setScaleX(scaleX);
376 if (isReordering(true)) {
377 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
378 mLastMotionX = p[0];
379 mLastMotionY = p[1];
380 updateDragViewTranslationDuringDrag();
381 }
382 }
383
384 // Convenience methods to get the actual width/height of the PagedView (since it is measured
385 // to be larger to account for the minimum possible scale)
386 int getViewportWidth() {
387 return mViewport.width();
388 }
389 int getViewportHeight() {
390 return mViewport.height();
391 }
392
393 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
394 // PagedView both horizontally and vertically
395 int getViewportOffsetX() {
396 return (getMeasuredWidth() - getViewportWidth()) / 2;
397 }
398
399 int getViewportOffsetY() {
400 return (getMeasuredHeight() - getViewportHeight()) / 2;
401 }
402
Adam Cohenedb40762013-07-18 16:45:45 -0700403 PageIndicator getPageIndicator() {
404 return mPageIndicator;
405 }
406
Winson Chung86f77532010-08-24 11:08:22 -0700407 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
408 mPageSwitchListener = pageSwitchListener;
409 if (mPageSwitchListener != null) {
410 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700411 }
412 }
413
414 /**
Winson Chung52aee602013-01-30 12:01:02 -0800415 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
416 */
417 public boolean isLayoutRtl() {
418 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
419 }
420
421 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700422 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
423 * out pages.
424 */
425 protected void setDataIsReady() {
426 mIsDataReady = true;
427 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700428
Winson Chungf0ea4d32011-06-06 14:27:16 -0700429 protected boolean isDataReady() {
430 return mIsDataReady;
431 }
432
433 /**
Winson Chung86f77532010-08-24 11:08:22 -0700434 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700435 *
Winson Chung86f77532010-08-24 11:08:22 -0700436 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700437 */
Winson Chung86f77532010-08-24 11:08:22 -0700438 int getCurrentPage() {
439 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700440 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700441
Winson Chung360e63f2012-04-27 13:48:05 -0700442 int getNextPage() {
443 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
444 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700445
Winson Chung86f77532010-08-24 11:08:22 -0700446 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700447 return getChildCount();
448 }
449
Winson Chung86f77532010-08-24 11:08:22 -0700450 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700451 return getChildAt(index);
452 }
453
Adam Cohenae4f1552011-10-20 00:15:42 -0700454 protected int indexToPage(int index) {
455 return index;
456 }
457
Winson Chung321e9ee2010-08-09 13:37:56 -0700458 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800459 * Updates the scroll of the current page immediately to its final scroll position. We use this
460 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
461 * the previous tab page.
462 */
463 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700464 // If the current page is invalid, just reset the scroll position to zero
465 int newX = 0;
466 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700467 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700468 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800469 scrollTo(newX, 0);
470 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800471 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800472 }
473
474 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700475 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
476 * ends, {@link #resumeScrolling()} should be called, along with
477 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
478 */
479 void pauseScrolling() {
480 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700481 }
482
483 /**
484 * Enables scrolling again.
485 * @see #pauseScrolling()
486 */
487 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700488 }
489 /**
Winson Chung86f77532010-08-24 11:08:22 -0700490 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700491 */
Winson Chung86f77532010-08-24 11:08:22 -0700492 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800493 if (!mScroller.isFinished()) {
494 mScroller.abortAnimation();
495 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800496 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
497 // the default
498 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800499 return;
500 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700501
Adam Cohene61a9a22013-06-11 15:45:31 -0700502 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700503 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700504 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700505 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800506 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700507 }
508
Michael Jurka0142d492010-08-25 17:46:15 -0700509 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700510 if (mPageSwitchListener != null) {
511 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700512 }
Winson Chungd2be3812013-07-16 11:11:32 -0700513
514 // Update the page indicator (when we aren't reordering)
515 if (mPageIndicator != null && !isReordering(false)) {
516 mPageIndicator.setActiveMarker(getNextPage());
517 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700518 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800519 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700520 if (!mIsPageMoving) {
521 mIsPageMoving = true;
522 onPageBeginMoving();
523 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700524 }
525
Michael Jurkace7e05f2011-02-01 22:02:35 -0800526 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700527 if (mIsPageMoving) {
528 mIsPageMoving = false;
529 onPageEndMoving();
530 }
Michael Jurka0142d492010-08-25 17:46:15 -0700531 }
532
Adam Cohen26976d92011-03-22 15:33:33 -0700533 protected boolean isPageMoving() {
534 return mIsPageMoving;
535 }
536
Michael Jurka0142d492010-08-25 17:46:15 -0700537 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700538 protected void onPageBeginMoving() {
539 }
540
541 // a method that subclasses can override to add behavior
542 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700543 }
544
Winson Chung321e9ee2010-08-09 13:37:56 -0700545 /**
Winson Chung86f77532010-08-24 11:08:22 -0700546 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700547 *
548 * @param l The listener used to respond to long clicks.
549 */
550 @Override
551 public void setOnLongClickListener(OnLongClickListener l) {
552 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700553 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700554 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700555 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700556 }
557 }
558
559 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800560 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700561 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800562 }
563
564 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700565 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700566 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800567 mUnboundedScrollX = x;
568
Adam Cohen0ffac432013-07-10 11:19:26 -0700569 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
570 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
571 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800572 super.scrollTo(0, y);
573 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700574 if (isRtl) {
575 overScroll(x - mMaxScrollX);
576 } else {
577 overScroll(x);
578 }
Adam Cohen68d73932010-11-15 10:50:58 -0800579 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700580 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800581 super.scrollTo(mMaxScrollX, y);
582 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700583 if (isRtl) {
584 overScroll(x);
585 } else {
586 overScroll(x - mMaxScrollX);
587 }
Adam Cohen68d73932010-11-15 10:50:58 -0800588 }
589 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800590 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800591 super.scrollTo(x, y);
592 }
593
Michael Jurka0142d492010-08-25 17:46:15 -0700594 mTouchX = x;
595 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700596
597 // Update the last motion events when scrolling
598 if (isReordering(true)) {
599 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
600 mLastMotionX = p[0];
601 mLastMotionY = p[1];
602 updateDragViewTranslationDuringDrag();
603 }
Michael Jurka0142d492010-08-25 17:46:15 -0700604 }
605
606 // we moved this functionality to a helper function so SmoothPagedView can reuse it
607 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700608 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700609 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700610 if (getScrollX() != mScroller.getCurrX()
611 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700612 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700613 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
614 }
Michael Jurka0142d492010-08-25 17:46:15 -0700615 invalidate();
616 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700617 } else if (mNextPage != INVALID_PAGE) {
618 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700619 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700620 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700621
Winson Chung9c0565f2013-07-19 13:49:06 -0700622 // Load the associated pages if necessary
623 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
624 loadAssociatedPages(mCurrentPage);
625 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
626 }
627
Adam Cohen73aa9752010-11-24 16:26:58 -0800628 // We don't want to trigger a page end moving unless the page has settled
629 // and the user has stopped scrolling
630 if (mTouchState == TOUCH_STATE_REST) {
631 pageEndMoving();
632 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700633
Adam Cohen7d30a372013-07-01 17:03:59 -0700634 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700635 // Notify the user when the page changes
636 AccessibilityManager accessibilityManager = (AccessibilityManager)
637 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
638 if (accessibilityManager.isEnabled()) {
639 AccessibilityEvent ev =
640 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
641 ev.getText().add(getCurrentPageDescription());
642 sendAccessibilityEventUnchecked(ev);
643 }
Michael Jurka0142d492010-08-25 17:46:15 -0700644 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700645 }
Michael Jurka0142d492010-08-25 17:46:15 -0700646 return false;
647 }
648
649 @Override
650 public void computeScroll() {
651 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700652 }
653
Adam Cohen7d30a372013-07-01 17:03:59 -0700654 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
655 return mTopAlignPageWhenShrinkingForBouncer;
656 }
657
Adam Cohen96d30a12013-07-16 18:13:21 -0700658 public static class LayoutParams extends ViewGroup.LayoutParams {
659 public boolean isFullScreenPage = false;
660
661 /**
662 * {@inheritDoc}
663 */
664 public LayoutParams(int width, int height) {
665 super(width, height);
666 }
667
668 public LayoutParams(ViewGroup.LayoutParams source) {
669 super(source);
670 }
671 }
672
673 protected LayoutParams generateDefaultLayoutParams() {
674 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
675 }
676
Adam Cohenedb40762013-07-18 16:45:45 -0700677 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700678 LayoutParams lp = generateDefaultLayoutParams();
679 lp.isFullScreenPage = true;
680 super.addView(page, 0, lp);
681 }
682
Winson Chung321e9ee2010-08-09 13:37:56 -0700683 @Override
684 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700685 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700686 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
687 return;
688 }
689
Adam Cohen7d30a372013-07-01 17:03:59 -0700690 // We measure the dimensions of the PagedView to be larger than the pages so that when we
691 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700692 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
693 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
694 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700695 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700696 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
697 // viewport, we can be at most one and a half screens offset once we scale down
698 DisplayMetrics dm = getResources().getDisplayMetrics();
699 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
700 int parentWidthSize = (int) (1.5f * maxSize);
701 int parentHeightSize = maxSize;
702 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
703 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
704 mViewport.set(0, 0, widthSize, heightSize);
705
706 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
707 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
708 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700709 }
710
Winson Chung8aad6102012-05-11 16:27:49 -0700711 // Return early if we aren't given a proper dimension
712 if (widthSize <= 0 || heightSize <= 0) {
713 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
714 return;
715 }
716
Adam Lesinski6b879f02010-11-04 16:15:23 -0700717 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
718 * of the All apps view on XLarge displays to not take up more space then it needs. Width
719 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
720 * each page to have the same width.
721 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700722 final int verticalPadding = getPaddingTop() + getPaddingBottom();
723 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700724
725 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700726 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700727 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700728 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
729 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
730 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
731 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700732 final int childCount = getChildCount();
733 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700734 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700735 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700736 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
737
738 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700739 int childHeightMode;
740 int childWidth;
741 int childHeight;
742
743 if (!lp.isFullScreenPage) {
744 if (lp.width == LayoutParams.WRAP_CONTENT) {
745 childWidthMode = MeasureSpec.AT_MOST;
746 } else {
747 childWidthMode = MeasureSpec.EXACTLY;
748 }
749
750 if (lp.height == LayoutParams.WRAP_CONTENT) {
751 childHeightMode = MeasureSpec.AT_MOST;
752 } else {
753 childHeightMode = MeasureSpec.EXACTLY;
754 }
755
756 childWidth = widthSize - horizontalPadding;
757 childHeight = heightSize - verticalPadding;
758
Michael Jurka5f1c5092010-09-03 14:15:02 -0700759 } else {
760 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700761 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700762
763 childWidth = getViewportWidth();
764 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700765 }
766
767 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700768 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
769 final int childHeightMeasureSpec =
770 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700771 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700772 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700773 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700774
Winson Chunga128a7b2012-04-30 15:23:15 -0700775 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700776 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700777 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700778 // The gap between pages in the PagedView should be equal to the gap from the page
779 // to the edge of the screen (so it is not visible in the current screen). To
780 // account for unequal padding on each side of the paged view, we take the maximum
781 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700782 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700783 int spacing = Math.max(offset, widthSize - offset -
784 getChildAt(0).getMeasuredWidth());
785 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700786 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700787 }
788 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700789 }
790
Adam Cohen60b07122011-11-14 17:26:06 -0800791 public void setPageSpacing(int pageSpacing) {
792 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700793 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800794 }
795
Winson Chung321e9ee2010-08-09 13:37:56 -0700796 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700797 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700798 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700799 return;
800 }
801
Winson Chung785d2eb2011-04-14 16:08:02 -0700802 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700803 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700804
Adam Cohenedb40762013-07-18 16:45:45 -0700805 int screenWidth = getViewportWidth();
806
Adam Cohen7d30a372013-07-01 17:03:59 -0700807 int offsetX = getViewportOffsetX();
808 int offsetY = getViewportOffsetY();
809
810 // Update the viewport offsets
811 mViewport.offset(offsetX, offsetY);
812
Adam Cohen0ffac432013-07-10 11:19:26 -0700813 final boolean isRtl = isLayoutRtl();
814
815 final int startIndex = isRtl ? childCount - 1 : 0;
816 final int endIndex = isRtl ? -1 : childCount;
817 final int delta = isRtl ? -1 : 1;
818
Adam Cohen7d30a372013-07-01 17:03:59 -0700819 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700820 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
821
822 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
823 mPageScrolls = new int[getChildCount()];
824 }
825
Adam Cohen0ffac432013-07-10 11:19:26 -0700826 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700827 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700828 LayoutParams lp = (LayoutParams) child.getLayoutParams();
829 int childTop;
830
831 if (lp.isFullScreenPage) {
832 childTop = offsetY;
833 } else {
834 childTop = offsetY + getPaddingTop();
835 if (mCenterPagesVertically) {
836 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
837 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700838 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700839
Winson Chung321e9ee2010-08-09 13:37:56 -0700840 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700841 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700842 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800843
Winson Chung785d2eb2011-04-14 16:08:02 -0700844 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700845 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800846 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700847
848 // We assume the left and right padding are equal, and hence center the pages
849 // horizontally
850 int scrollOffset = false ? 0 : (getViewportWidth() - childWidth) / 2;
851 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
852
Adam Cohen9c4949e2010-10-05 12:27:22 -0700853 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700854 }
855 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700856
857 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
858 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800859 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700860 setHorizontalScrollBarEnabled(true);
861 mFirstLayout = false;
862 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700863
864 if (childCount > 0) {
865 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700866 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700867 } else {
868 mMaxScrollX = 0;
869 }
870
871 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
872 !mDeferringForDelete) {
873 setCurrentPage(getNextPage());
874 }
875 mChildCountOnLastLayout = getChildCount();
Winson Chunge3193b92010-09-10 11:44:42 -0700876 }
877
Adam Cohenf34bab52010-09-30 14:11:56 -0700878 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700879 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
880
881 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700882 for (int i = 0; i < getChildCount(); i++) {
883 View child = getChildAt(i);
884 if (child != null) {
885 float scrollProgress = getScrollProgress(screenCenter, child, i);
886 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800887 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700888 }
889 }
890 invalidate();
891 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700892 }
893
Winson Chunge3193b92010-09-10 11:44:42 -0700894 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700895 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700896 // Update the page indicator, we don't update the page indicator as we
897 // add/remove pages
898 if (mPageIndicator != null && !isReordering(false)) {
899 mPageIndicator.addMarker(indexOfChild(child));
900 }
901
Adam Cohen2591f6a2011-10-25 14:36:40 -0700902 // This ensures that when children are added, they get the correct transforms / alphas
903 // in accordance with any scroll effects.
904 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700905 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700906
Adam Cohen2591f6a2011-10-25 14:36:40 -0700907 invalidate();
908 }
909
Michael Jurka8b805b12012-04-18 14:23:14 -0700910 @Override
911 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700912 mForceScreenScrolled = true;
913 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700914 }
915
Winson Chungd2be3812013-07-16 11:11:32 -0700916 private void removeMarkerForView(int index) {
917 // Update the page indicator, we don't update the page indicator as we
918 // add/remove pages
919 if (mPageIndicator != null && !isReordering(false)) {
920 mPageIndicator.removeMarker(index);
921 }
922 }
923
924 @Override
925 public void removeView(View v) {
926 // XXX: We should find a better way to hook into this before the view
927 // gets removed form its parent...
928 removeMarkerForView(indexOfChild(v));
929 super.removeView(v);
930 }
931 @Override
932 public void removeViewInLayout(View v) {
933 // XXX: We should find a better way to hook into this before the view
934 // gets removed form its parent...
935 removeMarkerForView(indexOfChild(v));
936 super.removeViewInLayout(v);
937 }
938 @Override
939 public void removeViewAt(int index) {
940 // XXX: We should find a better way to hook into this before the view
941 // gets removed form its parent...
942 removeViewAt(index);
943 super.removeViewAt(index);
944 }
945 @Override
946 public void removeAllViewsInLayout() {
947 // Update the page indicator, we don't update the page indicator as we
948 // add/remove pages
949 if (mPageIndicator != null) {
950 mPageIndicator.removeAllMarkers();
951 }
952
953 super.removeAllViewsInLayout();
954 }
955
Adam Cohen73894962011-10-31 13:17:17 -0700956 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700957 if (index < 0 || index > getChildCount() - 1) return 0;
958
Adam Cohen0ffac432013-07-10 11:19:26 -0700959 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700960
Adam Cohenf698c6e2013-07-17 18:44:25 -0700961 if (isRtl) index = getChildCount() - index - 1;
962 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -0700963
Adam Cohenf698c6e2013-07-17 18:44:25 -0700964 return offset;
Adam Cohen73894962011-10-31 13:17:17 -0700965 }
966
Winson Chungc9ca2982013-07-19 12:07:38 -0700967 void getReorderablePages(int[] range) {
968 range[0] = 0;
969 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -0700970 }
971
Michael Jurkadde558b2011-11-09 22:09:06 -0800972 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -0700973 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -0700974 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -0700975
Michael Jurkac4fb9172010-09-02 17:19:20 -0700976 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -0700977 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -0700978 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -0700979 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -0700980
Winson Chungc9ca2982013-07-19 12:07:38 -0700981 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
982 View currPage = getPageAt(leftScreen);
983
984 // Check if the right edge of the page is in the viewport
985 mTmpIntPoint[0] = currPage.getMeasuredWidth();
986 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
987 if (mTmpIntPoint[0] < 0) {
988 break;
989 }
990 }
991 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
992 View currPage = getPageAt(rightScreen);
993
994 // Check if the left edge of the page is in the viewport
995 mTmpIntPoint[0] = 0;
996 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
997 if (mTmpIntPoint[0] >= viewportWidth) {
998 break;
999 }
1000 }
1001 range[0] = Math.max(0, leftScreen);
1002 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001003 } else {
1004 range[0] = -1;
1005 range[1] = -1;
1006 }
1007 }
1008
Michael Jurka920d7f42012-05-14 16:29:55 -07001009 protected boolean shouldDrawChild(View child) {
1010 return child.getAlpha() > 0;
1011 }
1012
Michael Jurkadde558b2011-11-09 22:09:06 -08001013 @Override
1014 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001015 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001016 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1017 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001018 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001019
1020 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001021 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1022 // set it for the next frame
1023 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001024 screenScrolled(screenCenter);
1025 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001026 }
1027
1028 // Find out which screens are visible; as an optimization we only call draw on them
1029 final int pageCount = getChildCount();
1030 if (pageCount > 0) {
1031 getVisiblePages(mTempVisiblePagesRange);
1032 final int leftScreen = mTempVisiblePagesRange[0];
1033 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001034 if (leftScreen != -1 && rightScreen != -1) {
1035 final long drawingTime = getDrawingTime();
1036 // Clip to the bounds
1037 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001038 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1039 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001040
Adam Cohen7d30a372013-07-01 17:03:59 -07001041 // Draw all the children, leaving the drag view for last
1042 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001043 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001044 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001045 if (mForceDrawAllChildrenNextFrame ||
1046 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001047 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001048 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001049 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001050 // Draw the drag view on top (if there is one)
1051 if (mDragView != null) {
1052 drawChild(canvas, mDragView, drawingTime);
1053 }
1054
Michael Jurka5e368ff2012-05-14 23:13:15 -07001055 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001056 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001057 }
Michael Jurka0142d492010-08-25 17:46:15 -07001058 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001059 }
1060
1061 @Override
1062 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001063 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001064 if (page != mCurrentPage || !mScroller.isFinished()) {
1065 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001066 return true;
1067 }
1068 return false;
1069 }
1070
1071 @Override
1072 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001073 int focusablePage;
1074 if (mNextPage != INVALID_PAGE) {
1075 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001076 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001077 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001078 }
Winson Chung86f77532010-08-24 11:08:22 -07001079 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001080 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001081 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001082 }
1083 return false;
1084 }
1085
1086 @Override
1087 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001088 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001089 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001090 if (getCurrentPage() > 0) {
1091 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001092 return true;
1093 }
1094 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001095 if (getCurrentPage() < getPageCount() - 1) {
1096 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001097 return true;
1098 }
1099 }
1100 return super.dispatchUnhandledMove(focused, direction);
1101 }
1102
1103 @Override
1104 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001105 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001106 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001107 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001108 }
1109 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001110 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001111 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001112 }
1113 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001114 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001115 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001116 }
1117 }
1118 }
1119
1120 /**
1121 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001122 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001123 *
Winson Chung86f77532010-08-24 11:08:22 -07001124 * This happens when live folders requery, and if they're off page, they
1125 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001126 */
1127 @Override
1128 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001129 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001130 View v = focused;
1131 while (true) {
1132 if (v == current) {
1133 super.focusableViewAvailable(focused);
1134 return;
1135 }
1136 if (v == this) {
1137 return;
1138 }
1139 ViewParent parent = v.getParent();
1140 if (parent instanceof View) {
1141 v = (View)v.getParent();
1142 } else {
1143 return;
1144 }
1145 }
1146 }
1147
1148 /**
1149 * {@inheritDoc}
1150 */
1151 @Override
1152 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1153 if (disallowIntercept) {
1154 // We need to make sure to cancel our long press if
1155 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001156 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001157 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001158 }
1159 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1160 }
1161
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001162 /**
1163 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1164 */
1165 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001166 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001167 if (isLayoutRtl()) {
1168 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001169 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001170 }
Adam Cohenedb40762013-07-18 16:45:45 -07001171 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001172 }
1173
1174 /**
1175 * Return true if a tap at (x, y) should trigger a flip to the next page.
1176 */
1177 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001178 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001179 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001180 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001181 }
1182 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001183 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001184 }
Winson Chung52aee602013-01-30 12:01:02 -08001185
Adam Cohen7d30a372013-07-01 17:03:59 -07001186 /** Returns whether x and y originated within the buffered viewport */
1187 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1188 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1189 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1190 return mTmpRect.contains(x, y);
1191 }
1192
1193 /** Returns whether x and y originated within the current page view bounds */
1194 private boolean isTouchPointInCurrentPage(int x, int y) {
1195 View v = getPageAt(getCurrentPage());
1196 if (v != null) {
1197 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1198 v.getBottom());
1199 return mTmpRect.contains(x, y);
1200 }
1201 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001202 }
1203
Winson Chung321e9ee2010-08-09 13:37:56 -07001204 @Override
1205 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001206 if (DISABLE_TOUCH_INTERACTION) {
1207 return false;
1208 }
1209
Winson Chung321e9ee2010-08-09 13:37:56 -07001210 /*
1211 * This method JUST determines whether we want to intercept the motion.
1212 * If we return true, onTouchEvent will be called and we do the actual
1213 * scrolling there.
1214 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001215 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001216
Winson Chung45e1d6e2010-11-09 17:19:49 -08001217 // Skip touch handling if there are no pages to swipe
1218 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1219
Winson Chung321e9ee2010-08-09 13:37:56 -07001220 /*
1221 * Shortcut the most recurring case: the user is in the dragging
1222 * state and he is moving his finger. We want to intercept this
1223 * motion.
1224 */
1225 final int action = ev.getAction();
1226 if ((action == MotionEvent.ACTION_MOVE) &&
1227 (mTouchState == TOUCH_STATE_SCROLLING)) {
1228 return true;
1229 }
1230
Winson Chung321e9ee2010-08-09 13:37:56 -07001231 switch (action & MotionEvent.ACTION_MASK) {
1232 case MotionEvent.ACTION_MOVE: {
1233 /*
1234 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1235 * whether the user has moved far enough from his original down touch.
1236 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001237 if (mActivePointerId != INVALID_POINTER) {
1238 determineScrollingStart(ev);
1239 break;
1240 }
1241 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1242 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1243 // i.e. fall through to the next case (don't break)
1244 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1245 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001246 }
1247
1248 case MotionEvent.ACTION_DOWN: {
1249 final float x = ev.getX();
1250 final float y = ev.getY();
1251 // Remember location of down touch
1252 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001253 mDownMotionY = y;
1254 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001255 mLastMotionX = x;
1256 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001257 float[] p = mapPointFromViewToParent(this, x, y);
1258 mParentDownMotionX = p[0];
1259 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001260 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001261 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001262 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001263
1264 // Determine if the down event is within the threshold to be an edge swipe
1265 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1266 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1267 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1268 mDownEventOnEdge = true;
1269 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001270
1271 /*
1272 * If being flinged and user touches the screen, initiate drag;
1273 * otherwise don't. mScroller.isFinished should be false when
1274 * being flinged.
1275 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001276 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001277 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1278 if (finishedScrolling) {
1279 mTouchState = TOUCH_STATE_REST;
1280 mScroller.abortAnimation();
1281 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001282 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1283 mTouchState = TOUCH_STATE_SCROLLING;
1284 } else {
1285 mTouchState = TOUCH_STATE_REST;
1286 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001287 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001288
Winson Chung86f77532010-08-24 11:08:22 -07001289 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001290 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001291 if (!DISABLE_TOUCH_SIDE_PAGES) {
1292 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1293 if (getChildCount() > 0) {
1294 if (hitsPreviousPage(x, y)) {
1295 mTouchState = TOUCH_STATE_PREV_PAGE;
1296 } else if (hitsNextPage(x, y)) {
1297 mTouchState = TOUCH_STATE_NEXT_PAGE;
1298 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001299 }
1300 }
1301 }
1302 break;
1303 }
1304
Winson Chung321e9ee2010-08-09 13:37:56 -07001305 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001306 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001307 resetTouchState();
1308 // Just intercept the touch event on up if we tap outside the strict viewport
1309 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1310 return true;
1311 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001312 break;
1313
1314 case MotionEvent.ACTION_POINTER_UP:
1315 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001316 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001317 break;
1318 }
1319
1320 /*
1321 * The only time we want to intercept motion events is if we are in the
1322 * drag mode.
1323 */
1324 return mTouchState != TOUCH_STATE_REST;
1325 }
1326
Adam Cohenf8d28232011-02-01 21:47:00 -08001327 protected void determineScrollingStart(MotionEvent ev) {
1328 determineScrollingStart(ev, 1.0f);
1329 }
1330
Winson Chung321e9ee2010-08-09 13:37:56 -07001331 /*
1332 * Determines if we should change the touch state to start scrolling after the
1333 * user moves their touch point too far.
1334 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001335 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001336 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001337 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001338 if (pointerIndex == -1) return;
1339
1340 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001341 final float x = ev.getX(pointerIndex);
1342 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001343 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1344
1345 // If we're only allowing edge swipes, we break out early if the down event wasn't
1346 // at the edge.
1347 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1348
Winson Chung321e9ee2010-08-09 13:37:56 -07001349 final int xDiff = (int) Math.abs(x - mLastMotionX);
1350 final int yDiff = (int) Math.abs(y - mLastMotionY);
1351
Adam Cohenf8d28232011-02-01 21:47:00 -08001352 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001353 boolean xPaged = xDiff > mPagingTouchSlop;
1354 boolean xMoved = xDiff > touchSlop;
1355 boolean yMoved = yDiff > touchSlop;
1356
Adam Cohenf8d28232011-02-01 21:47:00 -08001357 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001358 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001359 // Scroll if the user moved far enough along the X axis
1360 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001361 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001362 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001363 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001364 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001365 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1366 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001367 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001368 }
1369 }
1370
Adam Cohen7d30a372013-07-01 17:03:59 -07001371 protected float getMaxScrollProgress() {
1372 return 1.0f;
1373 }
1374
Adam Cohenf8d28232011-02-01 21:47:00 -08001375 protected void cancelCurrentPageLongPress() {
1376 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001377 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001378 // Try canceling the long press. It could also have been scheduled
1379 // by a distant descendant, so use the mAllowLongPress flag to block
1380 // everything
1381 final View currentPage = getPageAt(mCurrentPage);
1382 if (currentPage != null) {
1383 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001384 }
1385 }
1386 }
1387
Adam Cohen7d30a372013-07-01 17:03:59 -07001388 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1389 final int halfScreenSize = getViewportWidth() / 2;
1390
1391 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1392 screenCenter = Math.max(halfScreenSize, screenCenter);
1393
1394 return getScrollProgress(screenCenter, v, page);
1395 }
1396
Adam Cohenb5ba0972011-09-07 18:02:31 -07001397 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001398 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001399
Adam Cohen96d30a12013-07-16 18:13:21 -07001400 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001401 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001402
1403 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001404 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1405 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001406 return scrollProgress;
1407 }
1408
Adam Cohenedb40762013-07-18 16:45:45 -07001409 public int getScrollForPage(int index) {
1410 if (mPageScrolls == null || index >= mPageScrolls.length) {
1411 return 0;
1412 } else {
1413 return mPageScrolls[index];
1414 }
1415 }
1416
Adam Cohene0f66b52010-11-23 15:06:07 -08001417 // This curve determines how the effect of scrolling over the limits of the page dimishes
1418 // as the user pulls further and further from the bounds
1419 private float overScrollInfluenceCurve(float f) {
1420 f -= 1.0f;
1421 return f * f * f + 1.0f;
1422 }
1423
Adam Cohenb5ba0972011-09-07 18:02:31 -07001424 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001425 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001426
1427 // We want to reach the max over scroll effect when the user has
1428 // over scrolled half the size of the screen
1429 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1430
1431 if (f == 0) return;
1432
1433 // Clamp this factor, f, to -1 < f < 1
1434 if (Math.abs(f) >= 1) {
1435 f /= Math.abs(f);
1436 }
1437
1438 int overScrollAmount = (int) Math.round(f * screenSize);
1439 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001440 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001441 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001442 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001443 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001444 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001445 }
1446 invalidate();
1447 }
1448
1449 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001450 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001451
1452 float f = (amount / screenSize);
1453
1454 if (f == 0) return;
1455 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1456
Adam Cohen7bfc9792011-01-28 13:52:37 -08001457 // Clamp this factor, f, to -1 < f < 1
1458 if (Math.abs(f) >= 1) {
1459 f /= Math.abs(f);
1460 }
1461
Adam Cohene0f66b52010-11-23 15:06:07 -08001462 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001463 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001464 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001465 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001466 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001467 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001468 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001469 }
1470 invalidate();
1471 }
1472
Adam Cohenb5ba0972011-09-07 18:02:31 -07001473 protected void overScroll(float amount) {
1474 dampedOverScroll(amount);
1475 }
1476
Michael Jurkac5b262c2011-01-12 20:24:50 -08001477 protected float maxOverScroll() {
1478 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001479 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001480 float f = 1.0f;
1481 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1482 return OVERSCROLL_DAMP_FACTOR * f;
1483 }
1484
Winson Chung321e9ee2010-08-09 13:37:56 -07001485 @Override
1486 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001487 if (DISABLE_TOUCH_INTERACTION) {
1488 return false;
1489 }
1490
Winson Chung45e1d6e2010-11-09 17:19:49 -08001491 // Skip touch handling if there are no pages to swipe
1492 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1493
Michael Jurkab8f06722010-10-10 15:58:46 -07001494 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001495
1496 final int action = ev.getAction();
1497
1498 switch (action & MotionEvent.ACTION_MASK) {
1499 case MotionEvent.ACTION_DOWN:
1500 /*
1501 * If being flinged and user touches, stop the fling. isFinished
1502 * will be false if being flinged.
1503 */
1504 if (!mScroller.isFinished()) {
1505 mScroller.abortAnimation();
1506 }
1507
1508 // Remember where the motion event started
1509 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001510 mDownMotionY = mLastMotionY = ev.getY();
1511 mDownScrollX = getScrollX();
1512 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1513 mParentDownMotionX = p[0];
1514 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001515 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001516 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001517 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001518
1519 // Determine if the down event is within the threshold to be an edge swipe
1520 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1521 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1522 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1523 mDownEventOnEdge = true;
1524 }
1525
Michael Jurka0142d492010-08-25 17:46:15 -07001526 if (mTouchState == TOUCH_STATE_SCROLLING) {
1527 pageBeginMoving();
1528 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001529 break;
1530
1531 case MotionEvent.ACTION_MOVE:
1532 if (mTouchState == TOUCH_STATE_SCROLLING) {
1533 // Scroll to follow the motion event
1534 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001535
1536 if (pointerIndex == -1) return true;
1537
Winson Chung321e9ee2010-08-09 13:37:56 -07001538 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001539 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001540
Adam Cohenaefd4e12011-02-14 16:39:38 -08001541 mTotalMotionX += Math.abs(deltaX);
1542
Winson Chungc0844aa2011-02-02 15:25:58 -08001543 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1544 // keep the remainder because we are actually testing if we've moved from the last
1545 // scrolled position (which is discrete).
1546 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001547 mTouchX += deltaX;
1548 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1549 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001550 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001551 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001552 } else {
1553 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001554 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001555 mLastMotionX = x;
1556 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001557 } else {
1558 awakenScrollBars();
1559 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001560 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1561 // Update the last motion position
1562 mLastMotionX = ev.getX();
1563 mLastMotionY = ev.getY();
1564
1565 // Update the parent down so that our zoom animations take this new movement into
1566 // account
1567 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1568 mParentDownMotionX = pt[0];
1569 mParentDownMotionY = pt[1];
1570 updateDragViewTranslationDuringDrag();
1571
1572 // Find the closest page to the touch point
1573 final int dragViewIndex = indexOfChild(mDragView);
1574 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1575 getViewportWidth());
1576 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1577 + bufferSize);
1578 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1579 - bufferSize);
1580
1581 // Change the drag view if we are hovering over the drop target
1582 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1583 (int) mParentDownMotionX, (int) mParentDownMotionY);
1584 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1585
1586 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1587 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1588 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1589 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1590 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1591 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1592
1593 float parentX = mParentDownMotionX;
1594 int pageIndexToSnapTo = -1;
1595 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1596 pageIndexToSnapTo = dragViewIndex - 1;
1597 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1598 pageIndexToSnapTo = dragViewIndex + 1;
1599 }
1600
1601 final int pageUnderPointIndex = pageIndexToSnapTo;
1602 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1603 mTempVisiblePagesRange[0] = 0;
1604 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07001605 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001606 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1607 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1608 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1609 mSidePageHoverIndex = pageUnderPointIndex;
1610 mSidePageHoverRunnable = new Runnable() {
1611 @Override
1612 public void run() {
1613 // Update the down scroll position to account for the fact that the
1614 // current page is moved
Adam Cohenedb40762013-07-18 16:45:45 -07001615 mDownScrollX = getScrollForPage(pageUnderPointIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001616
1617 // Setup the scroll to the correct page before we swap the views
1618 snapToPage(pageUnderPointIndex);
1619
1620 // For each of the pages between the paged view and the drag view,
1621 // animate them from the previous position to the new position in
1622 // the layout (as a result of the drag view moving in the layout)
1623 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1624 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1625 dragViewIndex + 1 : pageUnderPointIndex;
1626 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1627 dragViewIndex - 1 : pageUnderPointIndex;
1628 for (int i = lowerIndex; i <= upperIndex; ++i) {
1629 View v = getChildAt(i);
1630 // dragViewIndex < pageUnderPointIndex, so after we remove the
1631 // drag view all subsequent views to pageUnderPointIndex will
1632 // shift down.
1633 int oldX = getViewportOffsetX() + getChildOffset(i);
1634 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1635
1636 // Animate the view translation from its old position to its new
1637 // position
1638 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1639 if (anim != null) {
1640 anim.cancel();
1641 }
1642
1643 v.setTranslationX(oldX - newX);
1644 anim = new AnimatorSet();
1645 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1646 anim.playTogether(
1647 ObjectAnimator.ofFloat(v, "translationX", 0f));
1648 anim.start();
1649 v.setTag(anim);
1650 }
1651
1652 removeView(mDragView);
1653 onRemoveView(mDragView, false);
1654 addView(mDragView, pageUnderPointIndex);
1655 onAddView(mDragView, pageUnderPointIndex);
1656 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001657 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001658 }
1659 };
1660 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1661 }
1662 } else {
1663 removeCallbacks(mSidePageHoverRunnable);
1664 mSidePageHoverIndex = -1;
1665 }
Adam Cohen564976a2010-10-13 18:52:07 -07001666 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001667 determineScrollingStart(ev);
1668 }
1669 break;
1670
1671 case MotionEvent.ACTION_UP:
1672 if (mTouchState == TOUCH_STATE_SCROLLING) {
1673 final int activePointerId = mActivePointerId;
1674 final int pointerIndex = ev.findPointerIndex(activePointerId);
1675 final float x = ev.getX(pointerIndex);
1676 final VelocityTracker velocityTracker = mVelocityTracker;
1677 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1678 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001679 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001680 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001681 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1682 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001683
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001684 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1685
Adam Cohen00481b32011-11-18 12:03:48 -08001686 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001687 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001688
Adam Cohenaefd4e12011-02-14 16:39:38 -08001689 // In the case that the page is moved far to one direction and then is flung
1690 // in the opposite direction, we use a threshold to determine whether we should
1691 // just return to the starting page, or if we should skip one further.
1692 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001693 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001694 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001695 returnToOriginalPage = true;
1696 }
1697
Adam Cohenaefd4e12011-02-14 16:39:38 -08001698 int finalPage;
1699 // We give flings precedence over large moves, which is why we short-circuit our
1700 // test for a large move if a fling has been registered. That is, a large
1701 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001702 final boolean isRtl = isLayoutRtl();
1703 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1704 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1705 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1706 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001707 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1708 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001709 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1710 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001711 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001712 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1713 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001714 } else {
1715 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001716 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001717 // at this point we have not moved beyond the touch slop
1718 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1719 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001720 int nextPage = Math.max(0, mCurrentPage - 1);
1721 if (nextPage != mCurrentPage) {
1722 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001723 } else {
1724 snapToDestination();
1725 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001726 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001727 // at this point we have not moved beyond the touch slop
1728 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1729 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001730 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1731 if (nextPage != mCurrentPage) {
1732 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001733 } else {
1734 snapToDestination();
1735 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001736 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1737 // Update the last motion position
1738 mLastMotionX = ev.getX();
1739 mLastMotionY = ev.getY();
1740
1741 // Update the parent down so that our zoom animations take this new movement into
1742 // account
1743 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1744 mParentDownMotionX = pt[0];
1745 mParentDownMotionY = pt[1];
1746 updateDragViewTranslationDuringDrag();
1747 boolean handledFling = false;
1748 if (!DISABLE_FLING_TO_DELETE) {
1749 // Check the velocity and see if we are flinging-to-delete
1750 PointF flingToDeleteVector = isFlingingToDelete();
1751 if (flingToDeleteVector != null) {
1752 onFlingToDelete(flingToDeleteVector);
1753 handledFling = true;
1754 }
1755 }
1756 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1757 (int) mParentDownMotionY)) {
1758 onDropToDelete();
1759 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001760 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001761 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001762 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001763
1764 // Remove the callback to wait for the side page hover timeout
1765 removeCallbacks(mSidePageHoverRunnable);
1766 // End any intermediate reordering states
1767 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001768 break;
1769
1770 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001771 if (mTouchState == TOUCH_STATE_SCROLLING) {
1772 snapToDestination();
1773 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001774 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001775 break;
1776
1777 case MotionEvent.ACTION_POINTER_UP:
1778 onSecondaryPointerUp(ev);
1779 break;
1780 }
1781
1782 return true;
1783 }
1784
Adam Cohen7d30a372013-07-01 17:03:59 -07001785 public void onFlingToDelete(View v) {}
1786 public void onRemoveView(View v, boolean deletePermanently) {}
1787 public void onRemoveViewAnimationCompleted() {}
1788 public void onAddView(View v, int index) {}
1789
1790 private void resetTouchState() {
1791 releaseVelocityTracker();
1792 endReordering();
1793 mTouchState = TOUCH_STATE_REST;
1794 mActivePointerId = INVALID_POINTER;
1795 mDownEventOnEdge = false;
1796 }
1797
1798 protected void onUnhandledTap(MotionEvent ev) {}
1799
Winson Chung185d7162011-02-28 13:47:29 -08001800 @Override
1801 public boolean onGenericMotionEvent(MotionEvent event) {
1802 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1803 switch (event.getAction()) {
1804 case MotionEvent.ACTION_SCROLL: {
1805 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1806 final float vscroll;
1807 final float hscroll;
1808 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1809 vscroll = 0;
1810 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1811 } else {
1812 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1813 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1814 }
1815 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001816 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1817 : (hscroll > 0 || vscroll > 0);
1818 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001819 scrollRight();
1820 } else {
1821 scrollLeft();
1822 }
1823 return true;
1824 }
1825 }
1826 }
1827 }
1828 return super.onGenericMotionEvent(event);
1829 }
1830
Michael Jurkab8f06722010-10-10 15:58:46 -07001831 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1832 if (mVelocityTracker == null) {
1833 mVelocityTracker = VelocityTracker.obtain();
1834 }
1835 mVelocityTracker.addMovement(ev);
1836 }
1837
1838 private void releaseVelocityTracker() {
1839 if (mVelocityTracker != null) {
1840 mVelocityTracker.recycle();
1841 mVelocityTracker = null;
1842 }
1843 }
1844
Winson Chung321e9ee2010-08-09 13:37:56 -07001845 private void onSecondaryPointerUp(MotionEvent ev) {
1846 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1847 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1848 final int pointerId = ev.getPointerId(pointerIndex);
1849 if (pointerId == mActivePointerId) {
1850 // This was our active pointer going up. Choose a new
1851 // active pointer and adjust accordingly.
1852 // TODO: Make this decision more intelligent.
1853 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1854 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1855 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001856 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001857 mActivePointerId = ev.getPointerId(newPointerIndex);
1858 if (mVelocityTracker != null) {
1859 mVelocityTracker.clear();
1860 }
1861 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001862 }
1863
Winson Chung321e9ee2010-08-09 13:37:56 -07001864 @Override
1865 public void requestChildFocus(View child, View focused) {
1866 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001867 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001868 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001869 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001870 }
1871 }
1872
Winson Chung1908d072011-02-24 18:09:44 -08001873 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001874 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001875 }
1876
Adam Cohen7d30a372013-07-01 17:03:59 -07001877 int getPageNearestToPoint(float x) {
1878 int index = 0;
1879 for (int i = 0; i < getChildCount(); ++i) {
1880 if (x < getChildAt(i).getRight() - getScrollX()) {
1881 return index;
1882 } else {
1883 index++;
1884 }
1885 }
1886 return Math.min(index, getChildCount() - 1);
1887 }
1888
Adam Cohend19d3ca2010-09-15 14:43:42 -07001889 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001890 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001891 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001892 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001893 final int childCount = getChildCount();
1894 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001895 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001896 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001897 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001898 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001899 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1900 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1901 minDistanceFromScreenCenter = distanceFromScreenCenter;
1902 minDistanceFromScreenCenterIndex = i;
1903 }
1904 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001905 return minDistanceFromScreenCenterIndex;
1906 }
1907
1908 protected void snapToDestination() {
1909 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001910 }
1911
Adam Cohene0f66b52010-11-23 15:06:07 -08001912 private static class ScrollInterpolator implements Interpolator {
1913 public ScrollInterpolator() {
1914 }
1915
1916 public float getInterpolation(float t) {
1917 t -= 1.0f;
1918 return t*t*t*t*t + 1;
1919 }
1920 }
1921
1922 // We want the duration of the page snap animation to be influenced by the distance that
1923 // the screen has to travel, however, we don't want this duration to be effected in a
1924 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1925 // of travel has on the overall snap duration.
1926 float distanceInfluenceForSnapDuration(float f) {
1927 f -= 0.5f; // center the values about 0.
1928 f *= 0.3f * Math.PI / 2.0f;
1929 return (float) Math.sin(f);
1930 }
1931
Michael Jurka0142d492010-08-25 17:46:15 -07001932 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001933 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001934 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001935
Adam Cohenedb40762013-07-18 16:45:45 -07001936 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08001937 int delta = newX - mUnboundedScrollX;
1938 int duration = 0;
1939
Adam Cohen265b9a62011-12-07 14:37:18 -08001940 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001941 // If the velocity is low enough, then treat this more as an automatic page advance
1942 // as opposed to an apparent physical response to flinging
1943 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1944 return;
1945 }
1946
1947 // Here we compute a "distance" that will be used in the computation of the overall
1948 // snap duration. This is a function of the actual distance that needs to be traveled;
1949 // we keep this value close to half screen size in order to reduce the variance in snap
1950 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001951 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001952 float distance = halfScreenSize + halfScreenSize *
1953 distanceInfluenceForSnapDuration(distanceRatio);
1954
1955 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001956 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001957
1958 // we want the page's snap velocity to approximately match the velocity at which the
1959 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001960 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1961 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001962
1963 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001964 }
1965
1966 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001967 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001968 }
1969
Adam Cohen7d30a372013-07-01 17:03:59 -07001970 protected void snapToPageImmediately(int whichPage) {
1971 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1972 }
1973
Michael Jurka0142d492010-08-25 17:46:15 -07001974 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001975 snapToPage(whichPage, duration, false);
1976 }
1977
1978 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07001979 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07001980
Adam Cohenedb40762013-07-18 16:45:45 -07001981 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08001982 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001983 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07001984 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07001985 }
1986
1987 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001988 snapToPage(whichPage, delta, duration, false);
1989 }
Michael Jurka0142d492010-08-25 17:46:15 -07001990
Adam Cohen7d30a372013-07-01 17:03:59 -07001991 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
1992 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07001993 View focusedChild = getFocusedChild();
1994 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07001995 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07001996 focusedChild.clearFocus();
1997 }
1998
1999 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002000 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002001 if (immediate) {
2002 duration = 0;
2003 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002004 duration = Math.abs(delta);
2005 }
2006
2007 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002008 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002009
Michael Jurka0142d492010-08-25 17:46:15 -07002010 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002011
2012 // Trigger a compute() to finish switching pages if necessary
2013 if (immediate) {
2014 computeScroll();
2015 }
2016
Winson Chung9c0565f2013-07-19 13:49:06 -07002017 // Defer loading associated pages until the scroll settles
2018 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2019
Adam Cohen7d30a372013-07-01 17:03:59 -07002020 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002021 invalidate();
2022 }
2023
Winson Chung321e9ee2010-08-09 13:37:56 -07002024 public void scrollLeft() {
2025 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002026 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002027 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002028 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002029 }
2030 }
2031
2032 public void scrollRight() {
2033 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002034 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002035 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002036 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002037 }
2038 }
2039
Winson Chung86f77532010-08-24 11:08:22 -07002040 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002041 int result = -1;
2042 if (v != null) {
2043 ViewParent vp = v.getParent();
2044 int count = getChildCount();
2045 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002046 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002047 return i;
2048 }
2049 }
2050 }
2051 return result;
2052 }
2053
2054 /**
2055 * @return True is long presses are still allowed for the current touch
2056 */
2057 public boolean allowLongPress() {
2058 return mAllowLongPress;
2059 }
2060
Michael Jurka0142d492010-08-25 17:46:15 -07002061 /**
2062 * Set true to allow long-press events to be triggered, usually checked by
2063 * {@link Launcher} to accept or block dpad-initiated long-presses.
2064 */
2065 public void setAllowLongPress(boolean allowLongPress) {
2066 mAllowLongPress = allowLongPress;
2067 }
2068
Winson Chung321e9ee2010-08-09 13:37:56 -07002069 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002070 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002071
2072 SavedState(Parcelable superState) {
2073 super(superState);
2074 }
2075
2076 private SavedState(Parcel in) {
2077 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002078 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002079 }
2080
2081 @Override
2082 public void writeToParcel(Parcel out, int flags) {
2083 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002084 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002085 }
2086
2087 public static final Parcelable.Creator<SavedState> CREATOR =
2088 new Parcelable.Creator<SavedState>() {
2089 public SavedState createFromParcel(Parcel in) {
2090 return new SavedState(in);
2091 }
2092
2093 public SavedState[] newArray(int size) {
2094 return new SavedState[size];
2095 }
2096 };
2097 }
2098
Winson Chungf314b0e2011-08-16 11:54:27 -07002099 protected void loadAssociatedPages(int page) {
2100 loadAssociatedPages(page, false);
2101 }
2102 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002103 if (mContentIsRefreshable) {
2104 final int count = getChildCount();
2105 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002106 int lowerPageBound = getAssociatedLowerPageBound(page);
2107 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002108 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2109 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002110 // First, clear any pages that should no longer be loaded
2111 for (int i = 0; i < count; ++i) {
2112 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002113 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002114 if (layout.getPageChildCount() > 0) {
2115 layout.removeAllViewsOnPage();
2116 }
2117 mDirtyPageContent.set(i, true);
2118 }
2119 }
2120 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002121 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002122 if ((i != page) && immediateAndOnly) {
2123 continue;
2124 }
Michael Jurka0142d492010-08-25 17:46:15 -07002125 if (lowerPageBound <= i && i <= upperPageBound) {
2126 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002127 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002128 mDirtyPageContent.set(i, false);
2129 }
Winson Chung86f77532010-08-24 11:08:22 -07002130 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002131 }
2132 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002133 }
2134 }
2135
Winson Chunge3193b92010-09-10 11:44:42 -07002136 protected int getAssociatedLowerPageBound(int page) {
2137 return Math.max(0, page - 1);
2138 }
2139 protected int getAssociatedUpperPageBound(int page) {
2140 final int count = getChildCount();
2141 return Math.min(page + 1, count - 1);
2142 }
2143
Winson Chung86f77532010-08-24 11:08:22 -07002144 /**
2145 * This method is called ONLY to synchronize the number of pages that the paged view has.
2146 * To actually fill the pages with information, implement syncPageItems() below. It is
2147 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2148 * and therefore, individual page items do not need to be updated in this method.
2149 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002150 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002151
2152 /**
2153 * This method is called to synchronize the items that are on a particular page. If views on
2154 * the page can be reused, then they should be updated within this method.
2155 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002156 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002157
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002158 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002159 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002160 }
2161 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002162 invalidatePageData(currentPage, false);
2163 }
2164 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002165 if (!mIsDataReady) {
2166 return;
2167 }
2168
Michael Jurka0142d492010-08-25 17:46:15 -07002169 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002170 // Force all scrolling-related behavior to end
2171 mScroller.forceFinished(true);
2172 mNextPage = INVALID_PAGE;
2173
Michael Jurka0142d492010-08-25 17:46:15 -07002174 // Update all the pages
2175 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002176
Winson Chung5a808352011-06-27 19:08:49 -07002177 // We must force a measure after we've loaded the pages to update the content width and
2178 // to determine the full scroll width
2179 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2180 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2181
2182 // Set a new page as the current page if necessary
2183 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002184 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002185 }
2186
Michael Jurka0142d492010-08-25 17:46:15 -07002187 // Mark each of the pages as dirty
2188 final int count = getChildCount();
2189 mDirtyPageContent.clear();
2190 for (int i = 0; i < count; ++i) {
2191 mDirtyPageContent.add(true);
2192 }
2193
2194 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002195 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002196 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002197 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002198 }
Winson Chung007c6982011-06-14 13:27:53 -07002199
Adam Cohen7d30a372013-07-01 17:03:59 -07002200 // Animate the drag view back to the original position
2201 void animateDragViewToOriginalPosition() {
2202 if (mDragView != null) {
2203 AnimatorSet anim = new AnimatorSet();
2204 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2205 anim.playTogether(
2206 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2207 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2208 anim.addListener(new AnimatorListenerAdapter() {
2209 @Override
2210 public void onAnimationEnd(Animator animation) {
2211 onPostReorderingAnimationCompleted();
2212 }
2213 });
2214 anim.start();
2215 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002216 }
2217
Adam Cohen7d30a372013-07-01 17:03:59 -07002218 // "Zooms out" the PagedView to reveal more side pages
2219 protected boolean zoomOut() {
2220 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2221 mZoomInOutAnim.cancel();
2222 }
2223
2224 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2225 mZoomInOutAnim = new AnimatorSet();
2226 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2227 mZoomInOutAnim.playTogether(
2228 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2229 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2230 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2231 @Override
2232 public void onAnimationStart(Animator animation) {
2233 // Show the delete drop target
2234 if (mDeleteDropTarget != null) {
2235 mDeleteDropTarget.setVisibility(View.VISIBLE);
2236 mDeleteDropTarget.animate().alpha(1f)
2237 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2238 .setListener(new AnimatorListenerAdapter() {
2239 @Override
2240 public void onAnimationStart(Animator animation) {
2241 mDeleteDropTarget.setAlpha(0f);
2242 }
2243 });
2244 }
2245 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002246 @Override
2247 public void onAnimationEnd(Animator animation) {
2248 // Update the visible pages
2249 invalidate();
2250 }
Adam Cohen7d30a372013-07-01 17:03:59 -07002251 });
2252 mZoomInOutAnim.start();
2253 return true;
2254 }
2255 return false;
2256 }
2257
2258 protected void onStartReordering() {
2259 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2260 mTouchState = TOUCH_STATE_REORDERING;
2261 mIsReordering = true;
2262
2263 // Mark all the non-widget pages as invisible
Winson Chungc9ca2982013-07-19 12:07:38 -07002264 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002265 for (int i = 0; i < getPageCount(); ++i) {
2266 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2267 getPageAt(i).setAlpha(0f);
2268 }
2269 }
2270
2271 // We must invalidate to trigger a redraw to update the layers such that the drag view
2272 // is always drawn on top
2273 invalidate();
2274 }
2275
2276 private void onPostReorderingAnimationCompleted() {
2277 // Trigger the callback when reordering has settled
2278 --mPostReorderingPreZoomInRemainingAnimationCount;
2279 if (mPostReorderingPreZoomInRunnable != null &&
2280 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2281 mPostReorderingPreZoomInRunnable.run();
2282 mPostReorderingPreZoomInRunnable = null;
2283 }
2284 }
2285
2286 protected void onEndReordering() {
2287 mIsReordering = false;
2288
2289 // Mark all the non-widget pages as visible again
Winson Chungc9ca2982013-07-19 12:07:38 -07002290 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002291 for (int i = 0; i < getPageCount(); ++i) {
2292 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2293 getPageAt(i).setAlpha(1f);
2294 }
2295 }
2296 }
2297
2298 public boolean startReordering() {
2299 int dragViewIndex = getPageNearestToCenterOfScreen();
2300 mTempVisiblePagesRange[0] = 0;
2301 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07002302 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002303 mReorderingStarted = true;
2304
2305 // Check if we are within the reordering range
2306 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2307 dragViewIndex <= mTempVisiblePagesRange[1]) {
2308 if (zoomOut()) {
2309 // Find the drag view under the pointer
2310 mDragView = getChildAt(dragViewIndex);
2311
2312 onStartReordering();
2313 }
2314 return true;
2315 }
2316 return false;
2317 }
2318
2319 boolean isReordering(boolean testTouchState) {
2320 boolean state = mIsReordering;
2321 if (testTouchState) {
2322 state &= (mTouchState == TOUCH_STATE_REORDERING);
2323 }
2324 return state;
2325 }
2326 void endReordering() {
2327 // For simplicity, we call endReordering sometimes even if reordering was never started.
2328 // In that case, we don't want to do anything.
2329 if (!mReorderingStarted) return;
2330 mReorderingStarted = false;
2331
2332 // If we haven't flung-to-delete the current child, then we just animate the drag view
2333 // back into position
2334 final Runnable onCompleteRunnable = new Runnable() {
2335 @Override
2336 public void run() {
2337 onEndReordering();
2338 }
2339 };
2340 if (!mDeferringForDelete) {
2341 mPostReorderingPreZoomInRunnable = new Runnable() {
2342 public void run() {
2343 zoomIn(onCompleteRunnable);
2344 };
2345 };
2346
2347 mPostReorderingPreZoomInRemainingAnimationCount =
2348 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2349 // Snap to the current page
2350 snapToPage(indexOfChild(mDragView), 0);
2351 // Animate the drag view back to the front position
2352 animateDragViewToOriginalPosition();
2353 } else {
2354 // Handled in post-delete-animation-callbacks
2355 }
2356 }
2357
2358 // "Zooms in" the PagedView to highlight the current page
2359 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2360 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2361 mZoomInOutAnim.cancel();
2362 }
2363 if (getScaleX() < 1f || getScaleY() < 1f) {
2364 mZoomInOutAnim = new AnimatorSet();
2365 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2366 mZoomInOutAnim.playTogether(
2367 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2368 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2369 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2370 @Override
2371 public void onAnimationStart(Animator animation) {
2372 // Hide the delete drop target
2373 if (mDeleteDropTarget != null) {
2374 mDeleteDropTarget.animate().alpha(0f)
2375 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2376 .setListener(new AnimatorListenerAdapter() {
2377 @Override
2378 public void onAnimationEnd(Animator animation) {
2379 mDeleteDropTarget.setVisibility(View.GONE);
2380 }
2381 });
2382 }
2383 }
2384 @Override
2385 public void onAnimationCancel(Animator animation) {
2386 mDragView = null;
2387 }
2388 @Override
2389 public void onAnimationEnd(Animator animation) {
2390 mDragView = null;
2391 if (onCompleteRunnable != null) {
2392 onCompleteRunnable.run();
2393 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002394 // Update the visible pages
2395 invalidate();
Adam Cohen7d30a372013-07-01 17:03:59 -07002396 }
2397 });
2398 mZoomInOutAnim.start();
2399 return true;
2400 } else {
2401 if (onCompleteRunnable != null) {
2402 onCompleteRunnable.run();
2403 }
2404 }
2405 return false;
2406 }
2407
2408 /*
2409 * Flinging to delete - IN PROGRESS
2410 */
2411 private PointF isFlingingToDelete() {
2412 ViewConfiguration config = ViewConfiguration.get(getContext());
2413 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2414
2415 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2416 // Do a quick dot product test to ensure that we are flinging upwards
2417 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2418 mVelocityTracker.getYVelocity());
2419 PointF upVec = new PointF(0f, -1f);
2420 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2421 (vel.length() * upVec.length()));
2422 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2423 return vel;
2424 }
2425 }
2426 return null;
2427 }
2428
2429 /**
2430 * Creates an animation from the current drag view along its current velocity vector.
2431 * For this animation, the alpha runs for a fixed duration and we update the position
2432 * progressively.
2433 */
2434 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2435 private View mDragView;
2436 private PointF mVelocity;
2437 private Rect mFrom;
2438 private long mPrevTime;
2439 private float mFriction;
2440
2441 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2442
2443 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2444 long startTime, float friction) {
2445 mDragView = dragView;
2446 mVelocity = vel;
2447 mFrom = from;
2448 mPrevTime = startTime;
2449 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2450 }
2451
2452 @Override
2453 public void onAnimationUpdate(ValueAnimator animation) {
2454 float t = ((Float) animation.getAnimatedValue()).floatValue();
2455 long curTime = AnimationUtils.currentAnimationTimeMillis();
2456
2457 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2458 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2459
2460 mDragView.setTranslationX(mFrom.left);
2461 mDragView.setTranslationY(mFrom.top);
2462 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2463
2464 mVelocity.x *= mFriction;
2465 mVelocity.y *= mFriction;
2466 mPrevTime = curTime;
2467 }
2468 };
2469
2470 private static final int ANIM_TAG_KEY = 100;
2471
2472 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2473 return new Runnable() {
2474 @Override
2475 public void run() {
2476 int dragViewIndex = indexOfChild(dragView);
2477
2478 // For each of the pages around the drag view, animate them from the previous
2479 // position to the new position in the layout (as a result of the drag view moving
2480 // in the layout)
2481 // NOTE: We can make an assumption here because we have side-bound pages that we
2482 // will always have pages to animate in from the left
Winson Chungc9ca2982013-07-19 12:07:38 -07002483 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002484 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2485 boolean slideFromLeft = (isLastWidgetPage ||
2486 dragViewIndex > mTempVisiblePagesRange[0]);
2487
2488 // Setup the scroll to the correct page before we swap the views
2489 if (slideFromLeft) {
2490 snapToPageImmediately(dragViewIndex - 1);
2491 }
2492
2493 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2494 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2495 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2496 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2497 ArrayList<Animator> animations = new ArrayList<Animator>();
2498 for (int i = lowerIndex; i <= upperIndex; ++i) {
2499 View v = getChildAt(i);
2500 // dragViewIndex < pageUnderPointIndex, so after we remove the
2501 // drag view all subsequent views to pageUnderPointIndex will
2502 // shift down.
2503 int oldX = 0;
2504 int newX = 0;
2505 if (slideFromLeft) {
2506 if (i == 0) {
2507 // Simulate the page being offscreen with the page spacing
2508 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2509 - mPageSpacing;
2510 } else {
2511 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2512 }
2513 newX = getViewportOffsetX() + getChildOffset(i);
2514 } else {
2515 oldX = getChildOffset(i) - getChildOffset(i - 1);
2516 newX = 0;
2517 }
2518
2519 // Animate the view translation from its old position to its new
2520 // position
2521 AnimatorSet anim = (AnimatorSet) v.getTag();
2522 if (anim != null) {
2523 anim.cancel();
2524 }
2525
2526 // Note: Hacky, but we want to skip any optimizations to not draw completely
2527 // hidden views
2528 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2529 v.setTranslationX(oldX - newX);
2530 anim = new AnimatorSet();
2531 anim.playTogether(
2532 ObjectAnimator.ofFloat(v, "translationX", 0f),
2533 ObjectAnimator.ofFloat(v, "alpha", 1f));
2534 animations.add(anim);
2535 v.setTag(ANIM_TAG_KEY, anim);
2536 }
2537
2538 AnimatorSet slideAnimations = new AnimatorSet();
2539 slideAnimations.playTogether(animations);
2540 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2541 slideAnimations.addListener(new AnimatorListenerAdapter() {
2542 @Override
2543 public void onAnimationEnd(Animator animation) {
2544 final Runnable onCompleteRunnable = new Runnable() {
2545 @Override
2546 public void run() {
2547 mDeferringForDelete = false;
2548 onEndReordering();
2549 onRemoveViewAnimationCompleted();
2550 }
2551 };
2552 zoomIn(onCompleteRunnable);
2553 }
2554 });
2555 slideAnimations.start();
2556
2557 removeView(dragView);
2558 onRemoveView(dragView, true);
2559 }
2560 };
2561 }
2562
2563 public void onFlingToDelete(PointF vel) {
2564 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2565
2566 // NOTE: Because it takes time for the first frame of animation to actually be
2567 // called and we expect the animation to be a continuation of the fling, we have
2568 // to account for the time that has elapsed since the fling finished. And since
2569 // we don't have a startDelay, we will always get call to update when we call
2570 // start() (which we want to ignore).
2571 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2572 private int mCount = -1;
2573 private long mStartTime;
2574 private float mOffset;
2575 /* Anonymous inner class ctor */ {
2576 mStartTime = startTime;
2577 }
2578
2579 @Override
2580 public float getInterpolation(float t) {
2581 if (mCount < 0) {
2582 mCount++;
2583 } else if (mCount == 0) {
2584 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2585 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2586 mCount++;
2587 }
2588 return Math.min(1f, mOffset + t);
2589 }
2590 };
2591
2592 final Rect from = new Rect();
2593 final View dragView = mDragView;
2594 from.left = (int) dragView.getTranslationX();
2595 from.top = (int) dragView.getTranslationY();
2596 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2597 from, startTime, FLING_TO_DELETE_FRICTION);
2598
2599 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2600
2601 // Create and start the animation
2602 ValueAnimator mDropAnim = new ValueAnimator();
2603 mDropAnim.setInterpolator(tInterpolator);
2604 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2605 mDropAnim.setFloatValues(0f, 1f);
2606 mDropAnim.addUpdateListener(updateCb);
2607 mDropAnim.addListener(new AnimatorListenerAdapter() {
2608 public void onAnimationEnd(Animator animation) {
2609 onAnimationEndRunnable.run();
2610 }
2611 });
2612 mDropAnim.start();
2613 mDeferringForDelete = true;
2614 }
2615
2616 /* Drag to delete */
2617 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2618 if (mDeleteDropTarget != null) {
2619 mAltTmpRect.set(0, 0, 0, 0);
2620 View parent = (View) mDeleteDropTarget.getParent();
2621 if (parent != null) {
2622 parent.getGlobalVisibleRect(mAltTmpRect);
2623 }
2624 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2625 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2626 return mTmpRect.contains(x, y);
2627 }
2628 return false;
2629 }
2630
2631 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2632
2633 private void onDropToDelete() {
2634 final View dragView = mDragView;
2635
2636 final float toScale = 0f;
2637 final float toAlpha = 0f;
2638
2639 // Create and start the complex animation
2640 ArrayList<Animator> animations = new ArrayList<Animator>();
2641 AnimatorSet motionAnim = new AnimatorSet();
2642 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2643 motionAnim.playTogether(
2644 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2645 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2646 animations.add(motionAnim);
2647
2648 AnimatorSet alphaAnim = new AnimatorSet();
2649 alphaAnim.setInterpolator(new LinearInterpolator());
2650 alphaAnim.playTogether(
2651 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2652 animations.add(alphaAnim);
2653
2654 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2655
2656 AnimatorSet anim = new AnimatorSet();
2657 anim.playTogether(animations);
2658 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2659 anim.addListener(new AnimatorListenerAdapter() {
2660 public void onAnimationEnd(Animator animation) {
2661 onAnimationEndRunnable.run();
2662 }
2663 });
2664 anim.start();
2665
2666 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002667 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002668
2669 /* Accessibility */
2670 @Override
2671 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2672 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002673 info.setScrollable(getPageCount() > 1);
2674 if (getCurrentPage() < getPageCount() - 1) {
2675 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2676 }
2677 if (getCurrentPage() > 0) {
2678 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2679 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002680 }
2681
2682 @Override
2683 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2684 super.onInitializeAccessibilityEvent(event);
2685 event.setScrollable(true);
2686 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2687 event.setFromIndex(mCurrentPage);
2688 event.setToIndex(mCurrentPage);
2689 event.setItemCount(getChildCount());
2690 }
2691 }
2692
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002693 @Override
2694 public boolean performAccessibilityAction(int action, Bundle arguments) {
2695 if (super.performAccessibilityAction(action, arguments)) {
2696 return true;
2697 }
2698 switch (action) {
2699 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2700 if (getCurrentPage() < getPageCount() - 1) {
2701 scrollRight();
2702 return true;
2703 }
2704 } break;
2705 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2706 if (getCurrentPage() > 0) {
2707 scrollLeft();
2708 return true;
2709 }
2710 } break;
2711 }
2712 return false;
2713 }
2714
Adam Cohen0ffac432013-07-10 11:19:26 -07002715 protected String getCurrentPageDescription() {
2716 return String.format(getContext().getString(R.string.default_scroll_format),
2717 getNextPage() + 1, getChildCount());
2718 }
2719
Winson Chungd11265e2011-08-30 13:37:23 -07002720 @Override
2721 public boolean onHoverEvent(android.view.MotionEvent event) {
2722 return true;
2723 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002724}