blob: 514ce931f81febe4c41a4b34ee3f163786740540 [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 Cohen9c4949e2010-10-05 12:27:22 -070027import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070028import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070029import android.graphics.Matrix;
30import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070031import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070032import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070033import android.os.Parcel;
34import android.os.Parcelable;
35import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070036import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070037import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080038import android.view.InputDevice;
39import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070040import android.view.MotionEvent;
41import android.view.VelocityTracker;
42import android.view.View;
43import android.view.ViewConfiguration;
44import android.view.ViewGroup;
45import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070046import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070047import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070049import android.view.animation.AnimationUtils;
50import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080051import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070052import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070053import android.widget.Scroller;
54
Winson Chung6a0f57d2011-06-29 20:10:49 -070055import java.util.ArrayList;
56
Winson Chung321e9ee2010-08-09 13:37:56 -070057/**
58 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070059 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070060 */
Michael Jurka8b805b12012-04-18 14:23:14 -070061public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070062 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070063 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070064 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070065
Winson Chung86f77532010-08-24 11:08:22 -070066 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070067 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070068
Adam Cohen7d30a372013-07-01 17:03:59 -070069 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070070 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070071 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070072
Adam Cohenb5ba0972011-09-07 18:02:31 -070073 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070074 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080075
Adam Cohenb64cb5a2011-02-15 13:53:42 -080076 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080077 // The page is moved more than halfway, automatically move to the next page on touch up.
78 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080079
Adam Cohen265b9a62011-12-07 14:37:18 -080080 // The following constants need to be scaled based on density. The scaled versions will be
81 // assigned to the corresponding member variables below.
82 private static final int FLING_THRESHOLD_VELOCITY = 500;
83 private static final int MIN_SNAP_VELOCITY = 1500;
84 private static final int MIN_FLING_VELOCITY = 250;
85
Adam Cohen7d30a372013-07-01 17:03:59 -070086 // We are disabling touch interaction of the widget region for factory ROM.
87 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070088 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070089 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070090
Adam Cohenf358a4b2013-07-23 16:47:31 -070091 private boolean mFreeScroll = false;
92 private int mFreeScrollMinScrollX = -1;
93 private int mFreeScrollMaxScrollX = -1;
94
Winson Chung8aad6102012-05-11 16:27:49 -070095 static final int AUTOMATIC_PAGE_SPACING = -1;
96
Adam Cohen265b9a62011-12-07 14:37:18 -080097 protected int mFlingThresholdVelocity;
98 protected int mMinFlingVelocity;
99 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700100
Adam Cohenb5ba0972011-09-07 18:02:31 -0700101 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700102 protected float mSmoothingTime;
103 protected float mTouchX;
104
105 protected boolean mFirstLayout = true;
106
107 protected int mCurrentPage;
Winson Chung8c87cd82013-07-23 16:20:10 -0700108 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700109 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700110
Michael Jurka0142d492010-08-25 17:46:15 -0700111 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800112 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700113 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700114 private VelocityTracker mVelocityTracker;
115
Adam Cohen7d30a372013-07-01 17:03:59 -0700116 private float mParentDownMotionX;
117 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700118 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700119 private float mDownMotionY;
120 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700121 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800122 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800123 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800124 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800125 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700126 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700127
128 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700129
Michael Jurka0142d492010-08-25 17:46:15 -0700130 protected final static int TOUCH_STATE_REST = 0;
131 protected final static int TOUCH_STATE_SCROLLING = 1;
132 protected final static int TOUCH_STATE_PREV_PAGE = 2;
133 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700134 protected final static int TOUCH_STATE_REORDERING = 4;
135
Adam Cohene45440e2010-10-14 18:33:38 -0700136 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700137
Michael Jurka0142d492010-08-25 17:46:15 -0700138 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700139 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700140
Michael Jurka0142d492010-08-25 17:46:15 -0700141 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700142
Michael Jurka7426c422010-11-11 15:23:47 -0800143 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700144 private int mPagingTouchSlop;
145 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700146 protected int mPageSpacing;
147 protected int mPageLayoutPaddingTop;
148 protected int mPageLayoutPaddingBottom;
149 protected int mPageLayoutPaddingLeft;
150 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700151 protected int mPageLayoutWidthGap;
152 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700153 protected int mCellCountX = 0;
154 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700155 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800156 protected boolean mAllowOverScroll = true;
157 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800158 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700159 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700160
Michael Jurka8b805b12012-04-18 14:23:14 -0700161 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800162 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
163 // the screens from continuing to translate beyond the normal bounds.
164 protected int mOverScrollX;
165
Michael Jurka5f1c5092010-09-03 14:15:02 -0700166 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700167
Michael Jurka5f1c5092010-09-03 14:15:02 -0700168 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700169
Winson Chung86f77532010-08-24 11:08:22 -0700170 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700171
Michael Jurkae326f182011-11-21 14:05:46 -0800172 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700173
Michael Jurka0142d492010-08-25 17:46:15 -0700174 // If true, syncPages and syncPageItems will be called to refresh pages
175 protected boolean mContentIsRefreshable = true;
176
177 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700178 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700179
180 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
181 // to switch to a new page
182 protected boolean mUsePagingTouchSlop = true;
183
Michael Jurka8b805b12012-04-18 14:23:14 -0700184 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700185 // (SmoothPagedView does this)
186 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700187 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700188
Patrick Dubroy1262e362010-10-06 15:49:50 -0700189 protected boolean mIsPageMoving = false;
190
Winson Chungf0ea4d32011-06-06 14:27:16 -0700191 // All syncs and layout passes are deferred until data is ready.
192 protected boolean mIsDataReady = false;
193
Adam Cohen7d30a372013-07-01 17:03:59 -0700194 protected boolean mAllowLongPress = true;
195
Winson Chungd2be3812013-07-16 11:11:32 -0700196 // Page Indicator
197 private int mPageIndicatorViewId;
198 private PageIndicator mPageIndicator;
Winson Chung007c6982011-06-14 13:27:53 -0700199
Adam Cohen7d30a372013-07-01 17:03:59 -0700200 // The viewport whether the pages are to be contained (the actual view may be larger than the
201 // viewport)
202 private Rect mViewport = new Rect();
203
204 // Reordering
205 // We use the min scale to determine how much to expand the actually PagedView measured
206 // dimensions such that when we are zoomed out, the view is not clipped
207 private int REORDERING_DROP_REPOSITION_DURATION = 200;
208 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
209 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700210 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700211 private float mMinScale = 1f;
212 protected View mDragView;
213 protected AnimatorSet mZoomInOutAnim;
214 private Runnable mSidePageHoverRunnable;
215 private int mSidePageHoverIndex = -1;
216 // This variable's scope is only for the duration of startReordering() and endReordering()
217 private boolean mReorderingStarted = false;
218 // This variable's scope is for the duration of startReordering() and after the zoomIn()
219 // animation after endReordering()
220 private boolean mIsReordering;
221 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
222 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
223 private int mPostReorderingPreZoomInRemainingAnimationCount;
224 private Runnable mPostReorderingPreZoomInRunnable;
225
Adam Cohen7d30a372013-07-01 17:03:59 -0700226 // Convenience/caching
227 private Matrix mTmpInvMatrix = new Matrix();
228 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700229 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700230 private Rect mTmpRect = new Rect();
231 private Rect mAltTmpRect = new Rect();
232
233 // Fling to delete
234 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
235 private float FLING_TO_DELETE_FRICTION = 0.035f;
236 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
237 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
238 protected int mFlingToDeleteThresholdVelocity = -1400;
239 // Drag to delete
240 private boolean mDeferringForDelete = false;
241 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
242 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
243
244 // Drop to delete
245 private View mDeleteDropTarget;
246
247 private boolean mAutoComputePageSpacing = false;
248 private boolean mRecomputePageSpacing = false;
249
250 // Bouncer
251 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700252
Winson Chung86f77532010-08-24 11:08:22 -0700253 public interface PageSwitchListener {
254 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700255 }
256
Winson Chung321e9ee2010-08-09 13:37:56 -0700257 public PagedView(Context context) {
258 this(context, null);
259 }
260
261 public PagedView(Context context, AttributeSet attrs) {
262 this(context, attrs, 0);
263 }
264
265 public PagedView(Context context, AttributeSet attrs, int defStyle) {
266 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700267
Adam Cohen9c4949e2010-10-05 12:27:22 -0700268 TypedArray a = context.obtainStyledAttributes(attrs,
269 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800270 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700271 if (mPageSpacing < 0) {
272 mAutoComputePageSpacing = mRecomputePageSpacing = true;
273 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700274 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800275 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700276 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800277 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700278 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800279 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700280 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800281 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700282 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700283 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700284 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700285 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700286 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700287 a.recycle();
288
Winson Chung321e9ee2010-08-09 13:37:56 -0700289 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700290 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700291 }
292
293 /**
294 * Initializes various states for this workspace.
295 */
Michael Jurka0142d492010-08-25 17:46:15 -0700296 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700297 mDirtyPageContent = new ArrayList<Boolean>();
298 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800299 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700300 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700301 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700302
303 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700304 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700305 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
306 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700307 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800308
Adam Cohen7d30a372013-07-01 17:03:59 -0700309 // Scale the fling-to-delete threshold by the density
310 mFlingToDeleteThresholdVelocity =
311 (int) (mFlingToDeleteThresholdVelocity * mDensity);
312
Adam Cohen265b9a62011-12-07 14:37:18 -0800313 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
314 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
315 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700316 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700317 }
318
Winson Chungd2be3812013-07-16 11:11:32 -0700319 protected void onAttachedToWindow() {
320 // Hook up the page indicator
321 ViewGroup parent = (ViewGroup) getParent();
322 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
323 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
324 mPageIndicator.removeAllMarkers();
Winson Chung82dfe582013-07-26 15:07:49 -0700325
326 ArrayList<Integer> markers = new ArrayList<Integer>();
327 for (int i = 0; i < getChildCount(); ++i) {
328 markers.add(getPageIndicatorMarker(i));
329 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700330
Winson Chung82dfe582013-07-26 15:07:49 -0700331 mPageIndicator.addMarkers(markers);
Adam Cohenf358a4b2013-07-23 16:47:31 -0700332 mPageIndicator.setOnClickListener((Launcher) getContext());
Winson Chungd2be3812013-07-16 11:11:32 -0700333 }
334 }
335
336 protected void onDetachedFromWindow() {
337 // Unhook the page indicator
338 mPageIndicator = null;
339 }
340
Adam Cohen7d30a372013-07-01 17:03:59 -0700341 void setDeleteDropTarget(View v) {
342 mDeleteDropTarget = v;
343 }
344
345 // Convenience methods to map points from self to parent and vice versa
346 float[] mapPointFromViewToParent(View v, float x, float y) {
347 mTmpPoint[0] = x;
348 mTmpPoint[1] = y;
349 v.getMatrix().mapPoints(mTmpPoint);
350 mTmpPoint[0] += v.getLeft();
351 mTmpPoint[1] += v.getTop();
352 return mTmpPoint;
353 }
354 float[] mapPointFromParentToView(View v, float x, float y) {
355 mTmpPoint[0] = x - v.getLeft();
356 mTmpPoint[1] = y - v.getTop();
357 v.getMatrix().invert(mTmpInvMatrix);
358 mTmpInvMatrix.mapPoints(mTmpPoint);
359 return mTmpPoint;
360 }
361
362 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700363 if (mDragView != null) {
364 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
365 (mDragViewBaselineLeft - mDragView.getLeft());
366 float y = mLastMotionY - mDownMotionY;
367 mDragView.setTranslationX(x);
368 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700369
Adam Cohenf358a4b2013-07-23 16:47:31 -0700370 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
371 + x + ", " + y);
372 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700373 }
374
375 public void setMinScale(float f) {
376 mMinScale = f;
377 requestLayout();
378 }
379
380 @Override
381 public void setScaleX(float scaleX) {
382 super.setScaleX(scaleX);
383 if (isReordering(true)) {
384 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
385 mLastMotionX = p[0];
386 mLastMotionY = p[1];
387 updateDragViewTranslationDuringDrag();
388 }
389 }
390
391 // Convenience methods to get the actual width/height of the PagedView (since it is measured
392 // to be larger to account for the minimum possible scale)
393 int getViewportWidth() {
394 return mViewport.width();
395 }
396 int getViewportHeight() {
397 return mViewport.height();
398 }
399
400 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
401 // PagedView both horizontally and vertically
402 int getViewportOffsetX() {
403 return (getMeasuredWidth() - getViewportWidth()) / 2;
404 }
405
406 int getViewportOffsetY() {
407 return (getMeasuredHeight() - getViewportHeight()) / 2;
408 }
409
Adam Cohenedb40762013-07-18 16:45:45 -0700410 PageIndicator getPageIndicator() {
411 return mPageIndicator;
412 }
Winson Chung82dfe582013-07-26 15:07:49 -0700413 protected int getPageIndicatorMarker(int pageIndex) {
414 return R.layout.page_indicator_marker;
415 }
Adam Cohenedb40762013-07-18 16:45:45 -0700416
Winson Chung86f77532010-08-24 11:08:22 -0700417 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
418 mPageSwitchListener = pageSwitchListener;
419 if (mPageSwitchListener != null) {
420 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700421 }
422 }
423
424 /**
Winson Chung52aee602013-01-30 12:01:02 -0800425 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
426 */
427 public boolean isLayoutRtl() {
428 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
429 }
430
431 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700432 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
433 * out pages.
434 */
435 protected void setDataIsReady() {
436 mIsDataReady = true;
437 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700438
Winson Chungf0ea4d32011-06-06 14:27:16 -0700439 protected boolean isDataReady() {
440 return mIsDataReady;
441 }
442
443 /**
Winson Chung86f77532010-08-24 11:08:22 -0700444 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700445 *
Winson Chung86f77532010-08-24 11:08:22 -0700446 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700447 */
Winson Chung86f77532010-08-24 11:08:22 -0700448 int getCurrentPage() {
449 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700450 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700451
Winson Chung360e63f2012-04-27 13:48:05 -0700452 int getNextPage() {
453 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
454 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700455
Winson Chung86f77532010-08-24 11:08:22 -0700456 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700457 return getChildCount();
458 }
459
Winson Chung86f77532010-08-24 11:08:22 -0700460 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700461 return getChildAt(index);
462 }
463
Adam Cohenae4f1552011-10-20 00:15:42 -0700464 protected int indexToPage(int index) {
465 return index;
466 }
467
Winson Chung321e9ee2010-08-09 13:37:56 -0700468 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800469 * Updates the scroll of the current page immediately to its final scroll position. We use this
470 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
471 * the previous tab page.
472 */
473 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700474 // If the current page is invalid, just reset the scroll position to zero
475 int newX = 0;
476 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700477 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700478 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800479 scrollTo(newX, 0);
480 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800481 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800482 }
483
484 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700485 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
486 * ends, {@link #resumeScrolling()} should be called, along with
487 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
488 */
489 void pauseScrolling() {
490 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700491 }
492
493 /**
494 * Enables scrolling again.
495 * @see #pauseScrolling()
496 */
497 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700498 }
499 /**
Winson Chung86f77532010-08-24 11:08:22 -0700500 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700501 */
Winson Chung86f77532010-08-24 11:08:22 -0700502 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800503 if (!mScroller.isFinished()) {
504 mScroller.abortAnimation();
505 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800506 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
507 // the default
508 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800509 return;
510 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700511
Adam Cohene61a9a22013-06-11 15:45:31 -0700512 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700513 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700514 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700515 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800516 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700517 }
518
Winson Chung8c87cd82013-07-23 16:20:10 -0700519 /**
520 * The restore page will be set in place of the current page at the next (likely first)
521 * layout.
522 */
523 void setRestorePage(int restorePage) {
524 mRestorePage = restorePage;
525 }
526
Michael Jurka0142d492010-08-25 17:46:15 -0700527 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700528 if (mPageSwitchListener != null) {
529 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700530 }
Winson Chungd2be3812013-07-16 11:11:32 -0700531
532 // Update the page indicator (when we aren't reordering)
533 if (mPageIndicator != null && !isReordering(false)) {
534 mPageIndicator.setActiveMarker(getNextPage());
535 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700536 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800537 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700538 if (!mIsPageMoving) {
539 mIsPageMoving = true;
540 onPageBeginMoving();
541 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700542 }
543
Michael Jurkace7e05f2011-02-01 22:02:35 -0800544 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700545 if (mIsPageMoving) {
546 mIsPageMoving = false;
547 onPageEndMoving();
548 }
Michael Jurka0142d492010-08-25 17:46:15 -0700549 }
550
Adam Cohen26976d92011-03-22 15:33:33 -0700551 protected boolean isPageMoving() {
552 return mIsPageMoving;
553 }
554
Michael Jurka0142d492010-08-25 17:46:15 -0700555 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700556 protected void onPageBeginMoving() {
557 }
558
559 // a method that subclasses can override to add behavior
560 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700561 }
562
Winson Chung321e9ee2010-08-09 13:37:56 -0700563 /**
Winson Chung86f77532010-08-24 11:08:22 -0700564 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700565 *
566 * @param l The listener used to respond to long clicks.
567 */
568 @Override
569 public void setOnLongClickListener(OnLongClickListener l) {
570 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700571 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700572 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700573 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700574 }
575 }
576
577 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800578 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700579 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800580 }
581
582 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700583 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700584 // In free scroll mode, we clamp the scrollX
585 if (mFreeScroll) {
586 x = Math.min(x, mFreeScrollMaxScrollX);
587 x = Math.max(x, mFreeScrollMinScrollX);
588 }
589
Adam Cohen0ffac432013-07-10 11:19:26 -0700590 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800591 mUnboundedScrollX = x;
592
Adam Cohen0ffac432013-07-10 11:19:26 -0700593 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
594 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
595 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800596 super.scrollTo(0, y);
597 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700598 if (isRtl) {
599 overScroll(x - mMaxScrollX);
600 } else {
601 overScroll(x);
602 }
Adam Cohen68d73932010-11-15 10:50:58 -0800603 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700604 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800605 super.scrollTo(mMaxScrollX, y);
606 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700607 if (isRtl) {
608 overScroll(x);
609 } else {
610 overScroll(x - mMaxScrollX);
611 }
Adam Cohen68d73932010-11-15 10:50:58 -0800612 }
613 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800614 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800615 super.scrollTo(x, y);
616 }
617
Michael Jurka0142d492010-08-25 17:46:15 -0700618 mTouchX = x;
619 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700620
621 // Update the last motion events when scrolling
622 if (isReordering(true)) {
623 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
624 mLastMotionX = p[0];
625 mLastMotionY = p[1];
626 updateDragViewTranslationDuringDrag();
627 }
Michael Jurka0142d492010-08-25 17:46:15 -0700628 }
629
630 // we moved this functionality to a helper function so SmoothPagedView can reuse it
631 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700632 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700633 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700634 if (getScrollX() != mScroller.getCurrX()
635 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700636 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700637 float scaleX = mFreeScroll ? getScaleX() : 1f;
638 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
639 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700640 }
Michael Jurka0142d492010-08-25 17:46:15 -0700641 invalidate();
642 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700643 } else if (mNextPage != INVALID_PAGE) {
644 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700645 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700646 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700647
Winson Chung9c0565f2013-07-19 13:49:06 -0700648 // Load the associated pages if necessary
649 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
650 loadAssociatedPages(mCurrentPage);
651 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
652 }
653
Adam Cohen73aa9752010-11-24 16:26:58 -0800654 // We don't want to trigger a page end moving unless the page has settled
655 // and the user has stopped scrolling
656 if (mTouchState == TOUCH_STATE_REST) {
657 pageEndMoving();
658 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700659
Adam Cohen7d30a372013-07-01 17:03:59 -0700660 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700661 // Notify the user when the page changes
662 AccessibilityManager accessibilityManager = (AccessibilityManager)
663 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
664 if (accessibilityManager.isEnabled()) {
665 AccessibilityEvent ev =
666 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
667 ev.getText().add(getCurrentPageDescription());
668 sendAccessibilityEventUnchecked(ev);
669 }
Michael Jurka0142d492010-08-25 17:46:15 -0700670 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700671 }
Michael Jurka0142d492010-08-25 17:46:15 -0700672 return false;
673 }
674
675 @Override
676 public void computeScroll() {
677 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700678 }
679
Adam Cohen7d30a372013-07-01 17:03:59 -0700680 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
681 return mTopAlignPageWhenShrinkingForBouncer;
682 }
683
Adam Cohen96d30a12013-07-16 18:13:21 -0700684 public static class LayoutParams extends ViewGroup.LayoutParams {
685 public boolean isFullScreenPage = false;
686
687 /**
688 * {@inheritDoc}
689 */
690 public LayoutParams(int width, int height) {
691 super(width, height);
692 }
693
694 public LayoutParams(ViewGroup.LayoutParams source) {
695 super(source);
696 }
697 }
698
699 protected LayoutParams generateDefaultLayoutParams() {
700 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
701 }
702
Adam Cohenedb40762013-07-18 16:45:45 -0700703 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700704 LayoutParams lp = generateDefaultLayoutParams();
705 lp.isFullScreenPage = true;
706 super.addView(page, 0, lp);
707 }
708
Winson Chung321e9ee2010-08-09 13:37:56 -0700709 @Override
710 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700711 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700712 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
713 return;
714 }
715
Adam Cohen7d30a372013-07-01 17:03:59 -0700716 // We measure the dimensions of the PagedView to be larger than the pages so that when we
717 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700718 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
719 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
720 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700721 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700722 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
723 // viewport, we can be at most one and a half screens offset once we scale down
724 DisplayMetrics dm = getResources().getDisplayMetrics();
725 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
726 int parentWidthSize = (int) (1.5f * maxSize);
727 int parentHeightSize = maxSize;
728 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
729 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
730 mViewport.set(0, 0, widthSize, heightSize);
731
732 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
733 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
734 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700735 }
736
Winson Chung8aad6102012-05-11 16:27:49 -0700737 // Return early if we aren't given a proper dimension
738 if (widthSize <= 0 || heightSize <= 0) {
739 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
740 return;
741 }
742
Adam Lesinski6b879f02010-11-04 16:15:23 -0700743 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
744 * of the All apps view on XLarge displays to not take up more space then it needs. Width
745 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
746 * each page to have the same width.
747 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700748 final int verticalPadding = getPaddingTop() + getPaddingBottom();
749 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700750
751 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700752 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700753 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700754 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
755 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
756 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
757 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700758 final int childCount = getChildCount();
759 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700760 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700761 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700762 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
763
764 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700765 int childHeightMode;
766 int childWidth;
767 int childHeight;
768
769 if (!lp.isFullScreenPage) {
770 if (lp.width == LayoutParams.WRAP_CONTENT) {
771 childWidthMode = MeasureSpec.AT_MOST;
772 } else {
773 childWidthMode = MeasureSpec.EXACTLY;
774 }
775
776 if (lp.height == LayoutParams.WRAP_CONTENT) {
777 childHeightMode = MeasureSpec.AT_MOST;
778 } else {
779 childHeightMode = MeasureSpec.EXACTLY;
780 }
781
782 childWidth = widthSize - horizontalPadding;
783 childHeight = heightSize - verticalPadding;
784
Michael Jurka5f1c5092010-09-03 14:15:02 -0700785 } else {
786 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700787 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700788
789 childWidth = getViewportWidth();
790 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700791 }
792
793 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700794 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
795 final int childHeightMeasureSpec =
796 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700797 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700798 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700799 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700800
Winson Chunga128a7b2012-04-30 15:23:15 -0700801 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700802 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700803 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700804 // The gap between pages in the PagedView should be equal to the gap from the page
805 // to the edge of the screen (so it is not visible in the current screen). To
806 // account for unequal padding on each side of the paged view, we take the maximum
807 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700808 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700809 int spacing = Math.max(offset, widthSize - offset -
810 getChildAt(0).getMeasuredWidth());
811 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700812 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700813 }
814 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700815 }
816
Adam Cohen60b07122011-11-14 17:26:06 -0800817 public void setPageSpacing(int pageSpacing) {
818 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700819 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800820 }
821
Winson Chung321e9ee2010-08-09 13:37:56 -0700822 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700823 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700825 return;
826 }
827
Winson Chung785d2eb2011-04-14 16:08:02 -0700828 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700829 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700830
Adam Cohenedb40762013-07-18 16:45:45 -0700831 int screenWidth = getViewportWidth();
832
Adam Cohen7d30a372013-07-01 17:03:59 -0700833 int offsetX = getViewportOffsetX();
834 int offsetY = getViewportOffsetY();
835
836 // Update the viewport offsets
837 mViewport.offset(offsetX, offsetY);
838
Adam Cohen0ffac432013-07-10 11:19:26 -0700839 final boolean isRtl = isLayoutRtl();
840
841 final int startIndex = isRtl ? childCount - 1 : 0;
842 final int endIndex = isRtl ? -1 : childCount;
843 final int delta = isRtl ? -1 : 1;
844
Adam Cohen7d30a372013-07-01 17:03:59 -0700845 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700846 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
847
848 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
849 mPageScrolls = new int[getChildCount()];
850 }
851
Adam Cohen0ffac432013-07-10 11:19:26 -0700852 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700853
Adam Cohen22f823d2011-09-01 17:22:18 -0700854 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700855 LayoutParams lp = (LayoutParams) child.getLayoutParams();
856 int childTop;
857
858 if (lp.isFullScreenPage) {
859 childTop = offsetY;
860 } else {
861 childTop = offsetY + getPaddingTop();
862 if (mCenterPagesVertically) {
863 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
864 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700865 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700866
Winson Chung321e9ee2010-08-09 13:37:56 -0700867 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700868 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700869 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800870
Winson Chung785d2eb2011-04-14 16:08:02 -0700871 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700872 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800873 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700874
875 // We assume the left and right padding are equal, and hence center the pages
876 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700877 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700878 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
879
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700880 if (i != endIndex - delta) {
881 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
882 childLeft += childWidth + nextScrollOffset;
883 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700884 }
885 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700886
887 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
888 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800889 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700890 setHorizontalScrollBarEnabled(true);
891 mFirstLayout = false;
892 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700893
894 if (childCount > 0) {
895 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700896 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700897 } else {
898 mMaxScrollX = 0;
899 }
900
901 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
902 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700903 if (mRestorePage > -1) {
904 setCurrentPage(mRestorePage);
905 mRestorePage = -1;
906 } else {
907 setCurrentPage(getNextPage());
908 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700909 }
910 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700911
912 if (isReordering(true)) {
913 updateDragViewTranslationDuringDrag();
914 }
Winson Chunge3193b92010-09-10 11:44:42 -0700915 }
916
Adam Cohenf34bab52010-09-30 14:11:56 -0700917 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700918 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
919
920 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700921 for (int i = 0; i < getChildCount(); i++) {
922 View child = getChildAt(i);
923 if (child != null) {
924 float scrollProgress = getScrollProgress(screenCenter, child, i);
925 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800926 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700927 }
928 }
929 invalidate();
930 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700931 }
932
Winson Chunge3193b92010-09-10 11:44:42 -0700933 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700934 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700935 // Update the page indicator, we don't update the page indicator as we
936 // add/remove pages
937 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700938 int pageIndex = indexOfChild(child);
939 mPageIndicator.addMarker(pageIndex, getPageIndicatorMarker(pageIndex));
Winson Chungd2be3812013-07-16 11:11:32 -0700940 }
941
Adam Cohen2591f6a2011-10-25 14:36:40 -0700942 // This ensures that when children are added, they get the correct transforms / alphas
943 // in accordance with any scroll effects.
944 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700945 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700946
Adam Cohen2591f6a2011-10-25 14:36:40 -0700947 invalidate();
948 }
949
Michael Jurka8b805b12012-04-18 14:23:14 -0700950 @Override
951 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700952 mForceScreenScrolled = true;
953 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700954 }
955
Winson Chungd2be3812013-07-16 11:11:32 -0700956 private void removeMarkerForView(int index) {
957 // Update the page indicator, we don't update the page indicator as we
958 // add/remove pages
959 if (mPageIndicator != null && !isReordering(false)) {
960 mPageIndicator.removeMarker(index);
961 }
962 }
963
964 @Override
965 public void removeView(View v) {
966 // XXX: We should find a better way to hook into this before the view
967 // gets removed form its parent...
968 removeMarkerForView(indexOfChild(v));
969 super.removeView(v);
970 }
971 @Override
972 public void removeViewInLayout(View v) {
973 // XXX: We should find a better way to hook into this before the view
974 // gets removed form its parent...
975 removeMarkerForView(indexOfChild(v));
976 super.removeViewInLayout(v);
977 }
978 @Override
979 public void removeViewAt(int index) {
980 // XXX: We should find a better way to hook into this before the view
981 // gets removed form its parent...
982 removeViewAt(index);
983 super.removeViewAt(index);
984 }
985 @Override
986 public void removeAllViewsInLayout() {
987 // Update the page indicator, we don't update the page indicator as we
988 // add/remove pages
989 if (mPageIndicator != null) {
990 mPageIndicator.removeAllMarkers();
991 }
992
993 super.removeAllViewsInLayout();
994 }
995
Adam Cohen73894962011-10-31 13:17:17 -0700996 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700997 if (index < 0 || index > getChildCount() - 1) return 0;
998
Adam Cohen0ffac432013-07-10 11:19:26 -0700999 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -07001000
Adam Cohenf698c6e2013-07-17 18:44:25 -07001001 if (isRtl) index = getChildCount() - index - 1;
1002 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001003
Adam Cohenf698c6e2013-07-17 18:44:25 -07001004 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001005 }
1006
Adam Cohenf358a4b2013-07-23 16:47:31 -07001007 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001008 range[0] = 0;
1009 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001010 }
1011
Michael Jurkadde558b2011-11-09 22:09:06 -08001012 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001013 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001014 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001015
Michael Jurkac4fb9172010-09-02 17:19:20 -07001016 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001017 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -07001018 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -07001019 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001020
Winson Chungc9ca2982013-07-19 12:07:38 -07001021 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
1022 View currPage = getPageAt(leftScreen);
1023
1024 // Check if the right edge of the page is in the viewport
1025 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Winson Chungc763c4e2013-07-19 13:49:06 -07001026 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001027 if (mTmpIntPoint[0] < 0) {
1028 break;
1029 }
1030 }
1031 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1032 View currPage = getPageAt(rightScreen);
1033
1034 // Check if the left edge of the page is in the viewport
1035 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001036 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001037 if (mTmpIntPoint[0] >= viewportWidth) {
1038 break;
1039 }
1040 }
1041 range[0] = Math.max(0, leftScreen);
1042 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001043 } else {
1044 range[0] = -1;
1045 range[1] = -1;
1046 }
1047 }
1048
Michael Jurka920d7f42012-05-14 16:29:55 -07001049 protected boolean shouldDrawChild(View child) {
1050 return child.getAlpha() > 0;
1051 }
1052
Michael Jurkadde558b2011-11-09 22:09:06 -08001053 @Override
1054 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001055 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001056 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1057 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001058 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001059
1060 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001061 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1062 // set it for the next frame
1063 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001064 screenScrolled(screenCenter);
1065 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001066 }
1067
1068 // Find out which screens are visible; as an optimization we only call draw on them
1069 final int pageCount = getChildCount();
1070 if (pageCount > 0) {
1071 getVisiblePages(mTempVisiblePagesRange);
1072 final int leftScreen = mTempVisiblePagesRange[0];
1073 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001074 if (leftScreen != -1 && rightScreen != -1) {
1075 final long drawingTime = getDrawingTime();
1076 // Clip to the bounds
1077 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001078 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1079 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001080
Adam Cohen7d30a372013-07-01 17:03:59 -07001081 // Draw all the children, leaving the drag view for last
1082 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001083 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001084 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001085 if (mForceDrawAllChildrenNextFrame ||
1086 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001087 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001088 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001089 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001090 // Draw the drag view on top (if there is one)
1091 if (mDragView != null) {
1092 drawChild(canvas, mDragView, drawingTime);
1093 }
1094
Michael Jurka5e368ff2012-05-14 23:13:15 -07001095 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001096 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001097 }
Michael Jurka0142d492010-08-25 17:46:15 -07001098 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001099 }
1100
1101 @Override
1102 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001103 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001104 if (page != mCurrentPage || !mScroller.isFinished()) {
1105 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001106 return true;
1107 }
1108 return false;
1109 }
1110
1111 @Override
1112 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001113 int focusablePage;
1114 if (mNextPage != INVALID_PAGE) {
1115 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001116 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001117 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001118 }
Winson Chung86f77532010-08-24 11:08:22 -07001119 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001120 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001121 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001122 }
1123 return false;
1124 }
1125
1126 @Override
1127 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001128 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001129 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001130 if (getCurrentPage() > 0) {
1131 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001132 return true;
1133 }
1134 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001135 if (getCurrentPage() < getPageCount() - 1) {
1136 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001137 return true;
1138 }
1139 }
1140 return super.dispatchUnhandledMove(focused, direction);
1141 }
1142
1143 @Override
1144 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001145 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001146 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001147 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001148 }
1149 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001150 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001151 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001152 }
1153 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001154 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001155 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001156 }
1157 }
1158 }
1159
1160 /**
1161 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001162 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001163 *
Winson Chung86f77532010-08-24 11:08:22 -07001164 * This happens when live folders requery, and if they're off page, they
1165 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001166 */
1167 @Override
1168 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001169 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001170 View v = focused;
1171 while (true) {
1172 if (v == current) {
1173 super.focusableViewAvailable(focused);
1174 return;
1175 }
1176 if (v == this) {
1177 return;
1178 }
1179 ViewParent parent = v.getParent();
1180 if (parent instanceof View) {
1181 v = (View)v.getParent();
1182 } else {
1183 return;
1184 }
1185 }
1186 }
1187
1188 /**
1189 * {@inheritDoc}
1190 */
1191 @Override
1192 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1193 if (disallowIntercept) {
1194 // We need to make sure to cancel our long press if
1195 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001196 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001197 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001198 }
1199 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1200 }
1201
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001202 /**
1203 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1204 */
1205 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001206 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001207 if (isLayoutRtl()) {
1208 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001209 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001210 }
Adam Cohenedb40762013-07-18 16:45:45 -07001211 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001212 }
1213
1214 /**
1215 * Return true if a tap at (x, y) should trigger a flip to the next page.
1216 */
1217 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001218 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001219 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001220 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001221 }
1222 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001223 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001224 }
Winson Chung52aee602013-01-30 12:01:02 -08001225
Adam Cohen7d30a372013-07-01 17:03:59 -07001226 /** Returns whether x and y originated within the buffered viewport */
1227 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1228 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1229 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1230 return mTmpRect.contains(x, y);
1231 }
1232
Winson Chung321e9ee2010-08-09 13:37:56 -07001233 @Override
1234 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001235 if (DISABLE_TOUCH_INTERACTION) {
1236 return false;
1237 }
1238
Winson Chung321e9ee2010-08-09 13:37:56 -07001239 /*
1240 * This method JUST determines whether we want to intercept the motion.
1241 * If we return true, onTouchEvent will be called and we do the actual
1242 * scrolling there.
1243 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001244 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001245
Winson Chung45e1d6e2010-11-09 17:19:49 -08001246 // Skip touch handling if there are no pages to swipe
1247 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1248
Winson Chung321e9ee2010-08-09 13:37:56 -07001249 /*
1250 * Shortcut the most recurring case: the user is in the dragging
1251 * state and he is moving his finger. We want to intercept this
1252 * motion.
1253 */
1254 final int action = ev.getAction();
1255 if ((action == MotionEvent.ACTION_MOVE) &&
1256 (mTouchState == TOUCH_STATE_SCROLLING)) {
1257 return true;
1258 }
1259
Winson Chung321e9ee2010-08-09 13:37:56 -07001260 switch (action & MotionEvent.ACTION_MASK) {
1261 case MotionEvent.ACTION_MOVE: {
1262 /*
1263 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1264 * whether the user has moved far enough from his original down touch.
1265 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001266 if (mActivePointerId != INVALID_POINTER) {
1267 determineScrollingStart(ev);
1268 break;
1269 }
1270 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1271 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1272 // i.e. fall through to the next case (don't break)
1273 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1274 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001275 }
1276
1277 case MotionEvent.ACTION_DOWN: {
1278 final float x = ev.getX();
1279 final float y = ev.getY();
1280 // Remember location of down touch
1281 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001282 mDownMotionY = y;
1283 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001284 mLastMotionX = x;
1285 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001286 float[] p = mapPointFromViewToParent(this, x, y);
1287 mParentDownMotionX = p[0];
1288 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001289 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001290 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001291 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001292
Winson Chung321e9ee2010-08-09 13:37:56 -07001293 /*
1294 * If being flinged and user touches the screen, initiate drag;
1295 * otherwise don't. mScroller.isFinished should be false when
1296 * being flinged.
1297 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001298 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001299 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1300 if (finishedScrolling) {
1301 mTouchState = TOUCH_STATE_REST;
1302 mScroller.abortAnimation();
1303 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001304 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1305 mTouchState = TOUCH_STATE_SCROLLING;
1306 } else {
1307 mTouchState = TOUCH_STATE_REST;
1308 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001309 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001310
Winson Chung86f77532010-08-24 11:08:22 -07001311 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001312 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001313 if (!DISABLE_TOUCH_SIDE_PAGES) {
1314 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1315 if (getChildCount() > 0) {
1316 if (hitsPreviousPage(x, y)) {
1317 mTouchState = TOUCH_STATE_PREV_PAGE;
1318 } else if (hitsNextPage(x, y)) {
1319 mTouchState = TOUCH_STATE_NEXT_PAGE;
1320 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001321 }
1322 }
1323 }
1324 break;
1325 }
1326
Winson Chung321e9ee2010-08-09 13:37:56 -07001327 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001328 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001329 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001330 break;
1331
1332 case MotionEvent.ACTION_POINTER_UP:
1333 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001334 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001335 break;
1336 }
1337
1338 /*
1339 * The only time we want to intercept motion events is if we are in the
1340 * drag mode.
1341 */
1342 return mTouchState != TOUCH_STATE_REST;
1343 }
1344
Adam Cohenf8d28232011-02-01 21:47:00 -08001345 protected void determineScrollingStart(MotionEvent ev) {
1346 determineScrollingStart(ev, 1.0f);
1347 }
1348
Winson Chung321e9ee2010-08-09 13:37:56 -07001349 /*
1350 * Determines if we should change the touch state to start scrolling after the
1351 * user moves their touch point too far.
1352 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001353 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001354 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001355 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001356 if (pointerIndex == -1) return;
1357
1358 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001359 final float x = ev.getX(pointerIndex);
1360 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001361 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1362
Winson Chung321e9ee2010-08-09 13:37:56 -07001363 final int xDiff = (int) Math.abs(x - mLastMotionX);
1364 final int yDiff = (int) Math.abs(y - mLastMotionY);
1365
Adam Cohenf8d28232011-02-01 21:47:00 -08001366 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001367 boolean xPaged = xDiff > mPagingTouchSlop;
1368 boolean xMoved = xDiff > touchSlop;
1369 boolean yMoved = yDiff > touchSlop;
1370
Adam Cohenf8d28232011-02-01 21:47:00 -08001371 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001372 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001373 // Scroll if the user moved far enough along the X axis
1374 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001375 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001376 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001377 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001378 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001379 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1380 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001381 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001382 }
1383 }
1384
Adam Cohen7d30a372013-07-01 17:03:59 -07001385 protected float getMaxScrollProgress() {
1386 return 1.0f;
1387 }
1388
Adam Cohenf8d28232011-02-01 21:47:00 -08001389 protected void cancelCurrentPageLongPress() {
1390 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001391 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001392 // Try canceling the long press. It could also have been scheduled
1393 // by a distant descendant, so use the mAllowLongPress flag to block
1394 // everything
1395 final View currentPage = getPageAt(mCurrentPage);
1396 if (currentPage != null) {
1397 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001398 }
1399 }
1400 }
1401
Adam Cohen7d30a372013-07-01 17:03:59 -07001402 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1403 final int halfScreenSize = getViewportWidth() / 2;
1404
1405 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1406 screenCenter = Math.max(halfScreenSize, screenCenter);
1407
1408 return getScrollProgress(screenCenter, v, page);
1409 }
1410
Adam Cohenb5ba0972011-09-07 18:02:31 -07001411 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001412 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001413
Adam Cohen96d30a12013-07-16 18:13:21 -07001414 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001415 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001416
1417 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001418 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1419 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001420 return scrollProgress;
1421 }
1422
Adam Cohenedb40762013-07-18 16:45:45 -07001423 public int getScrollForPage(int index) {
1424 if (mPageScrolls == null || index >= mPageScrolls.length) {
1425 return 0;
1426 } else {
1427 return mPageScrolls[index];
1428 }
1429 }
1430
Adam Cohene0f66b52010-11-23 15:06:07 -08001431 // This curve determines how the effect of scrolling over the limits of the page dimishes
1432 // as the user pulls further and further from the bounds
1433 private float overScrollInfluenceCurve(float f) {
1434 f -= 1.0f;
1435 return f * f * f + 1.0f;
1436 }
1437
Adam Cohenb5ba0972011-09-07 18:02:31 -07001438 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001439 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001440
1441 // We want to reach the max over scroll effect when the user has
1442 // over scrolled half the size of the screen
1443 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1444
1445 if (f == 0) return;
1446
1447 // Clamp this factor, f, to -1 < f < 1
1448 if (Math.abs(f) >= 1) {
1449 f /= Math.abs(f);
1450 }
1451
1452 int overScrollAmount = (int) Math.round(f * screenSize);
1453 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001454 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001455 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001456 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001457 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001458 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001459 }
1460 invalidate();
1461 }
1462
1463 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001464 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001465
1466 float f = (amount / screenSize);
1467
1468 if (f == 0) return;
1469 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1470
Adam Cohen7bfc9792011-01-28 13:52:37 -08001471 // Clamp this factor, f, to -1 < f < 1
1472 if (Math.abs(f) >= 1) {
1473 f /= Math.abs(f);
1474 }
1475
Adam Cohene0f66b52010-11-23 15:06:07 -08001476 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001477 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001478 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001479 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001480 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001481 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001482 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001483 }
1484 invalidate();
1485 }
1486
Adam Cohenb5ba0972011-09-07 18:02:31 -07001487 protected void overScroll(float amount) {
1488 dampedOverScroll(amount);
1489 }
1490
Michael Jurkac5b262c2011-01-12 20:24:50 -08001491 protected float maxOverScroll() {
1492 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001493 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001494 float f = 1.0f;
1495 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1496 return OVERSCROLL_DAMP_FACTOR * f;
1497 }
1498
Adam Cohenf358a4b2013-07-23 16:47:31 -07001499 protected void enableFreeScroll() {
1500 setEnableFreeScroll(true, -1);
1501 }
1502
1503 protected void disableFreeScroll(int snapPage) {
1504 setEnableFreeScroll(false, snapPage);
1505 }
1506
1507 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1508 mFreeScroll = freeScroll;
1509
1510 if (snapPage == -1) {
1511 snapPage = getPageNearestToCenterOfScreen();
1512 }
1513
1514 getOverviewModePages(mTempVisiblePagesRange);
1515 if (!mFreeScroll) {
1516 snapToPage(snapPage);
1517
1518 for (int i = 0; i < getPageCount(); ++i) {
1519 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
1520 getPageAt(i).setAlpha(1f);
1521 }
1522 }
1523 } else {
1524 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1525 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1526
1527 for (int i = 0; i < getPageCount(); ++i) {
1528 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
1529 getPageAt(i).setAlpha(0f);
1530 }
1531 }
1532
1533 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1534 setCurrentPage(mTempVisiblePagesRange[0]);
1535 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1536 setCurrentPage(mTempVisiblePagesRange[1]);
1537 }
1538 }
1539
1540 setEnableOverscroll(!freeScroll);
1541 }
1542
1543 private void setEnableOverscroll(boolean enable) {
1544 mAllowOverScroll = enable;
1545 }
1546
1547 int getNearestHoverOverPageIndex() {
1548 if (mDragView != null) {
1549 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1550 + mDragView.getTranslationX());
1551 getOverviewModePages(mTempVisiblePagesRange);
1552 int minDistance = Integer.MAX_VALUE;
1553 int minIndex = indexOfChild(mDragView);
1554 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1555 View page = getPageAt(i);
1556 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1557 int d = Math.abs(dragX - pageX);
1558 if (d < minDistance) {
1559 minIndex = i;
1560 minDistance = d;
1561 }
1562 }
1563 return minIndex;
1564 }
1565 return -1;
1566 }
1567
Winson Chung321e9ee2010-08-09 13:37:56 -07001568 @Override
1569 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001570 if (DISABLE_TOUCH_INTERACTION) {
1571 return false;
1572 }
1573
Winson Chung45e1d6e2010-11-09 17:19:49 -08001574 // Skip touch handling if there are no pages to swipe
1575 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1576
Michael Jurkab8f06722010-10-10 15:58:46 -07001577 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001578
1579 final int action = ev.getAction();
1580
1581 switch (action & MotionEvent.ACTION_MASK) {
1582 case MotionEvent.ACTION_DOWN:
1583 /*
1584 * If being flinged and user touches, stop the fling. isFinished
1585 * will be false if being flinged.
1586 */
1587 if (!mScroller.isFinished()) {
1588 mScroller.abortAnimation();
1589 }
1590
1591 // Remember where the motion event started
1592 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001593 mDownMotionY = mLastMotionY = ev.getY();
1594 mDownScrollX = getScrollX();
1595 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1596 mParentDownMotionX = p[0];
1597 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001598 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001599 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001600 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001601
Michael Jurka0142d492010-08-25 17:46:15 -07001602 if (mTouchState == TOUCH_STATE_SCROLLING) {
1603 pageBeginMoving();
1604 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001605 break;
1606
1607 case MotionEvent.ACTION_MOVE:
1608 if (mTouchState == TOUCH_STATE_SCROLLING) {
1609 // Scroll to follow the motion event
1610 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001611
1612 if (pointerIndex == -1) return true;
1613
Winson Chung321e9ee2010-08-09 13:37:56 -07001614 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001615 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001616
Adam Cohenaefd4e12011-02-14 16:39:38 -08001617 mTotalMotionX += Math.abs(deltaX);
1618
Winson Chungc0844aa2011-02-02 15:25:58 -08001619 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1620 // keep the remainder because we are actually testing if we've moved from the last
1621 // scrolled position (which is discrete).
1622 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001623 mTouchX += deltaX;
1624 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1625 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001626 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001627 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001628 } else {
1629 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001630 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001631 mLastMotionX = x;
1632 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001633 } else {
1634 awakenScrollBars();
1635 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001636 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1637 // Update the last motion position
1638 mLastMotionX = ev.getX();
1639 mLastMotionY = ev.getY();
1640
1641 // Update the parent down so that our zoom animations take this new movement into
1642 // account
1643 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1644 mParentDownMotionX = pt[0];
1645 mParentDownMotionY = pt[1];
1646 updateDragViewTranslationDuringDrag();
1647
1648 // Find the closest page to the touch point
1649 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001650
1651 // Change the drag view if we are hovering over the drop target
1652 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1653 (int) mParentDownMotionX, (int) mParentDownMotionY);
1654 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1655
Adam Cohen7d30a372013-07-01 17:03:59 -07001656 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1657 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1658 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1659 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1660
Adam Cohenf358a4b2013-07-23 16:47:31 -07001661 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1662 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1663 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001664 mTempVisiblePagesRange[0] = 0;
1665 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001666 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001667 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1668 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1669 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1670 mSidePageHoverIndex = pageUnderPointIndex;
1671 mSidePageHoverRunnable = new Runnable() {
1672 @Override
1673 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001674 // Setup the scroll to the correct page before we swap the views
1675 snapToPage(pageUnderPointIndex);
1676
1677 // For each of the pages between the paged view and the drag view,
1678 // animate them from the previous position to the new position in
1679 // the layout (as a result of the drag view moving in the layout)
1680 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1681 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1682 dragViewIndex + 1 : pageUnderPointIndex;
1683 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1684 dragViewIndex - 1 : pageUnderPointIndex;
1685 for (int i = lowerIndex; i <= upperIndex; ++i) {
1686 View v = getChildAt(i);
1687 // dragViewIndex < pageUnderPointIndex, so after we remove the
1688 // drag view all subsequent views to pageUnderPointIndex will
1689 // shift down.
1690 int oldX = getViewportOffsetX() + getChildOffset(i);
1691 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1692
1693 // Animate the view translation from its old position to its new
1694 // position
1695 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1696 if (anim != null) {
1697 anim.cancel();
1698 }
1699
1700 v.setTranslationX(oldX - newX);
1701 anim = new AnimatorSet();
1702 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1703 anim.playTogether(
1704 ObjectAnimator.ofFloat(v, "translationX", 0f));
1705 anim.start();
1706 v.setTag(anim);
1707 }
1708
1709 removeView(mDragView);
1710 onRemoveView(mDragView, false);
1711 addView(mDragView, pageUnderPointIndex);
1712 onAddView(mDragView, pageUnderPointIndex);
1713 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001714 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001715 }
1716 };
1717 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1718 }
1719 } else {
1720 removeCallbacks(mSidePageHoverRunnable);
1721 mSidePageHoverIndex = -1;
1722 }
Adam Cohen564976a2010-10-13 18:52:07 -07001723 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001724 determineScrollingStart(ev);
1725 }
1726 break;
1727
1728 case MotionEvent.ACTION_UP:
1729 if (mTouchState == TOUCH_STATE_SCROLLING) {
1730 final int activePointerId = mActivePointerId;
1731 final int pointerIndex = ev.findPointerIndex(activePointerId);
1732 final float x = ev.getX(pointerIndex);
1733 final VelocityTracker velocityTracker = mVelocityTracker;
1734 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1735 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001736 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001737 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001738 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1739 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001740
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001741 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1742
Adam Cohen00481b32011-11-18 12:03:48 -08001743 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001744 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001745
Adam Cohenf358a4b2013-07-23 16:47:31 -07001746 if (!mFreeScroll) {
1747 // In the case that the page is moved far to one direction and then is flung
1748 // in the opposite direction, we use a threshold to determine whether we should
1749 // just return to the starting page, or if we should skip one further.
1750 boolean returnToOriginalPage = false;
1751 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1752 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1753 returnToOriginalPage = true;
1754 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001755
Adam Cohenf358a4b2013-07-23 16:47:31 -07001756 int finalPage;
1757 // We give flings precedence over large moves, which is why we short-circuit our
1758 // test for a large move if a fling has been registered. That is, a large
1759 // move to the left and fling to the right will register as a fling to the right.
1760 final boolean isRtl = isLayoutRtl();
1761 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1762 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1763 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1764 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1765 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1766 snapToPageWithVelocity(finalPage, velocityX);
1767 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1768 (isFling && isVelocityXLeft)) &&
1769 mCurrentPage < getChildCount() - 1) {
1770 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1771 snapToPageWithVelocity(finalPage, velocityX);
1772 } else {
1773 snapToDestination();
1774 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1775 // at this point we have not moved beyond the touch slop
1776 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1777 // we can just page
1778 int nextPage = Math.max(0, mCurrentPage - 1);
1779 if (nextPage != mCurrentPage) {
1780 snapToPage(nextPage);
1781 } else {
1782 snapToDestination();
1783 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001784 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001785 if (!mScroller.isFinished()) {
1786 mScroller.abortAnimation();
1787 }
1788
1789 float scaleX = getScaleX();
1790 int vX = (int) (-velocityX * scaleX);
1791 int initialScrollX = (int) (getScrollX() * scaleX);
1792
1793 mScroller.fling(initialScrollX,
1794 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1795 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001796 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001797 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001798 // at this point we have not moved beyond the touch slop
1799 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1800 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001801 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1802 if (nextPage != mCurrentPage) {
1803 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001804 } else {
1805 snapToDestination();
1806 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001807 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1808 // Update the last motion position
1809 mLastMotionX = ev.getX();
1810 mLastMotionY = ev.getY();
1811
1812 // Update the parent down so that our zoom animations take this new movement into
1813 // account
1814 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1815 mParentDownMotionX = pt[0];
1816 mParentDownMotionY = pt[1];
1817 updateDragViewTranslationDuringDrag();
1818 boolean handledFling = false;
1819 if (!DISABLE_FLING_TO_DELETE) {
1820 // Check the velocity and see if we are flinging-to-delete
1821 PointF flingToDeleteVector = isFlingingToDelete();
1822 if (flingToDeleteVector != null) {
1823 onFlingToDelete(flingToDeleteVector);
1824 handledFling = true;
1825 }
1826 }
1827 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1828 (int) mParentDownMotionY)) {
1829 onDropToDelete();
1830 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001831 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001832 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001833 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001834
1835 // Remove the callback to wait for the side page hover timeout
1836 removeCallbacks(mSidePageHoverRunnable);
1837 // End any intermediate reordering states
1838 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001839 break;
1840
1841 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001842 if (mTouchState == TOUCH_STATE_SCROLLING) {
1843 snapToDestination();
1844 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001845 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001846 break;
1847
1848 case MotionEvent.ACTION_POINTER_UP:
1849 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001850 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001851 break;
1852 }
1853
1854 return true;
1855 }
1856
Adam Cohen7d30a372013-07-01 17:03:59 -07001857 public void onFlingToDelete(View v) {}
1858 public void onRemoveView(View v, boolean deletePermanently) {}
1859 public void onRemoveViewAnimationCompleted() {}
1860 public void onAddView(View v, int index) {}
1861
1862 private void resetTouchState() {
1863 releaseVelocityTracker();
1864 endReordering();
1865 mTouchState = TOUCH_STATE_REST;
1866 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001867 }
1868
1869 protected void onUnhandledTap(MotionEvent ev) {}
1870
Winson Chung185d7162011-02-28 13:47:29 -08001871 @Override
1872 public boolean onGenericMotionEvent(MotionEvent event) {
1873 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1874 switch (event.getAction()) {
1875 case MotionEvent.ACTION_SCROLL: {
1876 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1877 final float vscroll;
1878 final float hscroll;
1879 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1880 vscroll = 0;
1881 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1882 } else {
1883 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1884 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1885 }
1886 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001887 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1888 : (hscroll > 0 || vscroll > 0);
1889 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001890 scrollRight();
1891 } else {
1892 scrollLeft();
1893 }
1894 return true;
1895 }
1896 }
1897 }
1898 }
1899 return super.onGenericMotionEvent(event);
1900 }
1901
Michael Jurkab8f06722010-10-10 15:58:46 -07001902 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1903 if (mVelocityTracker == null) {
1904 mVelocityTracker = VelocityTracker.obtain();
1905 }
1906 mVelocityTracker.addMovement(ev);
1907 }
1908
1909 private void releaseVelocityTracker() {
1910 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001911 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001912 mVelocityTracker.recycle();
1913 mVelocityTracker = null;
1914 }
1915 }
1916
Winson Chung321e9ee2010-08-09 13:37:56 -07001917 private void onSecondaryPointerUp(MotionEvent ev) {
1918 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1919 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1920 final int pointerId = ev.getPointerId(pointerIndex);
1921 if (pointerId == mActivePointerId) {
1922 // This was our active pointer going up. Choose a new
1923 // active pointer and adjust accordingly.
1924 // TODO: Make this decision more intelligent.
1925 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1926 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1927 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001928 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001929 mActivePointerId = ev.getPointerId(newPointerIndex);
1930 if (mVelocityTracker != null) {
1931 mVelocityTracker.clear();
1932 }
1933 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001934 }
1935
Winson Chung321e9ee2010-08-09 13:37:56 -07001936 @Override
1937 public void requestChildFocus(View child, View focused) {
1938 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001939 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001940 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001941 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001942 }
1943 }
1944
Winson Chung1908d072011-02-24 18:09:44 -08001945 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001946 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001947 }
1948
Adam Cohen7d30a372013-07-01 17:03:59 -07001949 int getPageNearestToPoint(float x) {
1950 int index = 0;
1951 for (int i = 0; i < getChildCount(); ++i) {
1952 if (x < getChildAt(i).getRight() - getScrollX()) {
1953 return index;
1954 } else {
1955 index++;
1956 }
1957 }
1958 return Math.min(index, getChildCount() - 1);
1959 }
1960
Adam Cohend19d3ca2010-09-15 14:43:42 -07001961 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001962 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001963 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001964 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001965 final int childCount = getChildCount();
1966 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001967 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001968 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001969 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001970 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001971 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1972 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1973 minDistanceFromScreenCenter = distanceFromScreenCenter;
1974 minDistanceFromScreenCenterIndex = i;
1975 }
1976 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001977 return minDistanceFromScreenCenterIndex;
1978 }
1979
1980 protected void snapToDestination() {
1981 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001982 }
1983
Adam Cohene0f66b52010-11-23 15:06:07 -08001984 private static class ScrollInterpolator implements Interpolator {
1985 public ScrollInterpolator() {
1986 }
1987
1988 public float getInterpolation(float t) {
1989 t -= 1.0f;
1990 return t*t*t*t*t + 1;
1991 }
1992 }
1993
1994 // We want the duration of the page snap animation to be influenced by the distance that
1995 // the screen has to travel, however, we don't want this duration to be effected in a
1996 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1997 // of travel has on the overall snap duration.
1998 float distanceInfluenceForSnapDuration(float f) {
1999 f -= 0.5f; // center the values about 0.
2000 f *= 0.3f * Math.PI / 2.0f;
2001 return (float) Math.sin(f);
2002 }
2003
Michael Jurka0142d492010-08-25 17:46:15 -07002004 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002005 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002006 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002007
Adam Cohenedb40762013-07-18 16:45:45 -07002008 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002009 int delta = newX - mUnboundedScrollX;
2010 int duration = 0;
2011
Adam Cohen265b9a62011-12-07 14:37:18 -08002012 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002013 // If the velocity is low enough, then treat this more as an automatic page advance
2014 // as opposed to an apparent physical response to flinging
2015 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2016 return;
2017 }
2018
2019 // Here we compute a "distance" that will be used in the computation of the overall
2020 // snap duration. This is a function of the actual distance that needs to be traveled;
2021 // we keep this value close to half screen size in order to reduce the variance in snap
2022 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002023 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002024 float distance = halfScreenSize + halfScreenSize *
2025 distanceInfluenceForSnapDuration(distanceRatio);
2026
2027 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002028 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002029
2030 // we want the page's snap velocity to approximately match the velocity at which the
2031 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002032 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2033 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002034
2035 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002036 }
2037
2038 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002039 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002040 }
2041
Adam Cohen7d30a372013-07-01 17:03:59 -07002042 protected void snapToPageImmediately(int whichPage) {
2043 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2044 }
2045
Michael Jurka0142d492010-08-25 17:46:15 -07002046 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002047 snapToPage(whichPage, duration, false);
2048 }
2049
2050 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002051 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002052
Adam Cohenedb40762013-07-18 16:45:45 -07002053 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002054 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002055 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002056 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002057 }
2058
2059 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002060 snapToPage(whichPage, delta, duration, false);
2061 }
Michael Jurka0142d492010-08-25 17:46:15 -07002062
Adam Cohen7d30a372013-07-01 17:03:59 -07002063 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2064 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002065 View focusedChild = getFocusedChild();
2066 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002067 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002068 focusedChild.clearFocus();
2069 }
2070
2071 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002072 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002073 if (immediate) {
2074 duration = 0;
2075 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002076 duration = Math.abs(delta);
2077 }
2078
Adam Cohenf358a4b2013-07-23 16:47:31 -07002079 if (!mScroller.isFinished()) {
2080 mScroller.abortAnimation();
2081 }
Adam Cohen68d73932010-11-15 10:50:58 -08002082 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002083
Michael Jurka0142d492010-08-25 17:46:15 -07002084 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002085
2086 // Trigger a compute() to finish switching pages if necessary
2087 if (immediate) {
2088 computeScroll();
2089 }
2090
Winson Chung9c0565f2013-07-19 13:49:06 -07002091 // Defer loading associated pages until the scroll settles
2092 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2093
Adam Cohen7d30a372013-07-01 17:03:59 -07002094 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002095 invalidate();
2096 }
2097
Winson Chung321e9ee2010-08-09 13:37:56 -07002098 public void scrollLeft() {
2099 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002100 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002101 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002102 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002103 }
2104 }
2105
2106 public void scrollRight() {
2107 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002108 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002109 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002110 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002111 }
2112 }
2113
Winson Chung86f77532010-08-24 11:08:22 -07002114 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002115 int result = -1;
2116 if (v != null) {
2117 ViewParent vp = v.getParent();
2118 int count = getChildCount();
2119 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002120 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002121 return i;
2122 }
2123 }
2124 }
2125 return result;
2126 }
2127
2128 /**
2129 * @return True is long presses are still allowed for the current touch
2130 */
2131 public boolean allowLongPress() {
2132 return mAllowLongPress;
2133 }
2134
Michael Jurka0142d492010-08-25 17:46:15 -07002135 /**
2136 * Set true to allow long-press events to be triggered, usually checked by
2137 * {@link Launcher} to accept or block dpad-initiated long-presses.
2138 */
2139 public void setAllowLongPress(boolean allowLongPress) {
2140 mAllowLongPress = allowLongPress;
2141 }
2142
Winson Chung321e9ee2010-08-09 13:37:56 -07002143 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002144 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002145
2146 SavedState(Parcelable superState) {
2147 super(superState);
2148 }
2149
2150 private SavedState(Parcel in) {
2151 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002152 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002153 }
2154
2155 @Override
2156 public void writeToParcel(Parcel out, int flags) {
2157 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002158 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002159 }
2160
2161 public static final Parcelable.Creator<SavedState> CREATOR =
2162 new Parcelable.Creator<SavedState>() {
2163 public SavedState createFromParcel(Parcel in) {
2164 return new SavedState(in);
2165 }
2166
2167 public SavedState[] newArray(int size) {
2168 return new SavedState[size];
2169 }
2170 };
2171 }
2172
Winson Chungf314b0e2011-08-16 11:54:27 -07002173 protected void loadAssociatedPages(int page) {
2174 loadAssociatedPages(page, false);
2175 }
2176 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002177 if (mContentIsRefreshable) {
2178 final int count = getChildCount();
2179 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002180 int lowerPageBound = getAssociatedLowerPageBound(page);
2181 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002182 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2183 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002184 // First, clear any pages that should no longer be loaded
2185 for (int i = 0; i < count; ++i) {
2186 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002187 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002188 if (layout.getPageChildCount() > 0) {
2189 layout.removeAllViewsOnPage();
2190 }
2191 mDirtyPageContent.set(i, true);
2192 }
2193 }
2194 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002195 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002196 if ((i != page) && immediateAndOnly) {
2197 continue;
2198 }
Michael Jurka0142d492010-08-25 17:46:15 -07002199 if (lowerPageBound <= i && i <= upperPageBound) {
2200 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002201 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002202 mDirtyPageContent.set(i, false);
2203 }
Winson Chung86f77532010-08-24 11:08:22 -07002204 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002205 }
2206 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002207 }
2208 }
2209
Winson Chunge3193b92010-09-10 11:44:42 -07002210 protected int getAssociatedLowerPageBound(int page) {
2211 return Math.max(0, page - 1);
2212 }
2213 protected int getAssociatedUpperPageBound(int page) {
2214 final int count = getChildCount();
2215 return Math.min(page + 1, count - 1);
2216 }
2217
Winson Chung86f77532010-08-24 11:08:22 -07002218 /**
2219 * This method is called ONLY to synchronize the number of pages that the paged view has.
2220 * To actually fill the pages with information, implement syncPageItems() below. It is
2221 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2222 * and therefore, individual page items do not need to be updated in this method.
2223 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002224 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002225
2226 /**
2227 * This method is called to synchronize the items that are on a particular page. If views on
2228 * the page can be reused, then they should be updated within this method.
2229 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002230 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002231
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002232 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002233 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002234 }
2235 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002236 invalidatePageData(currentPage, false);
2237 }
2238 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002239 if (!mIsDataReady) {
2240 return;
2241 }
2242
Michael Jurka0142d492010-08-25 17:46:15 -07002243 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002244 // Force all scrolling-related behavior to end
2245 mScroller.forceFinished(true);
2246 mNextPage = INVALID_PAGE;
2247
Michael Jurka0142d492010-08-25 17:46:15 -07002248 // Update all the pages
2249 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002250
Winson Chung5a808352011-06-27 19:08:49 -07002251 // We must force a measure after we've loaded the pages to update the content width and
2252 // to determine the full scroll width
2253 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2254 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2255
2256 // Set a new page as the current page if necessary
2257 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002258 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002259 }
2260
Michael Jurka0142d492010-08-25 17:46:15 -07002261 // Mark each of the pages as dirty
2262 final int count = getChildCount();
2263 mDirtyPageContent.clear();
2264 for (int i = 0; i < count; ++i) {
2265 mDirtyPageContent.add(true);
2266 }
2267
2268 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002269 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002270 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002271 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002272 }
Winson Chung007c6982011-06-14 13:27:53 -07002273
Adam Cohen7d30a372013-07-01 17:03:59 -07002274 // Animate the drag view back to the original position
2275 void animateDragViewToOriginalPosition() {
2276 if (mDragView != null) {
2277 AnimatorSet anim = new AnimatorSet();
2278 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2279 anim.playTogether(
2280 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002281 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2282 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2283 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002284 anim.addListener(new AnimatorListenerAdapter() {
2285 @Override
2286 public void onAnimationEnd(Animator animation) {
2287 onPostReorderingAnimationCompleted();
2288 }
2289 });
2290 anim.start();
2291 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002292 }
2293
Adam Cohen7d30a372013-07-01 17:03:59 -07002294 protected void onStartReordering() {
2295 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2296 mTouchState = TOUCH_STATE_REORDERING;
2297 mIsReordering = true;
2298
Adam Cohen7d30a372013-07-01 17:03:59 -07002299 // We must invalidate to trigger a redraw to update the layers such that the drag view
2300 // is always drawn on top
2301 invalidate();
2302 }
2303
2304 private void onPostReorderingAnimationCompleted() {
2305 // Trigger the callback when reordering has settled
2306 --mPostReorderingPreZoomInRemainingAnimationCount;
2307 if (mPostReorderingPreZoomInRunnable != null &&
2308 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2309 mPostReorderingPreZoomInRunnable.run();
2310 mPostReorderingPreZoomInRunnable = null;
2311 }
2312 }
2313
2314 protected void onEndReordering() {
2315 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002316 }
2317
Adam Cohenf358a4b2013-07-23 16:47:31 -07002318 public boolean startReordering(View v) {
2319 int dragViewIndex = indexOfChild(v);//getPageNearestToCenterOfScreen();
Adam Cohen7d30a372013-07-01 17:03:59 -07002320 mTempVisiblePagesRange[0] = 0;
2321 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002322 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002323 mReorderingStarted = true;
2324
2325 // Check if we are within the reordering range
2326 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002327 dragViewIndex <= mTempVisiblePagesRange[1]) {
2328 // Find the drag view under the pointer
2329 mDragView = getChildAt(dragViewIndex);
2330 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2331 mDragViewBaselineLeft = mDragView.getLeft();
2332 disableFreeScroll(-1);
2333 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002334 return true;
2335 }
2336 return false;
2337 }
2338
2339 boolean isReordering(boolean testTouchState) {
2340 boolean state = mIsReordering;
2341 if (testTouchState) {
2342 state &= (mTouchState == TOUCH_STATE_REORDERING);
2343 }
2344 return state;
2345 }
2346 void endReordering() {
2347 // For simplicity, we call endReordering sometimes even if reordering was never started.
2348 // In that case, we don't want to do anything.
2349 if (!mReorderingStarted) return;
2350 mReorderingStarted = false;
2351
2352 // If we haven't flung-to-delete the current child, then we just animate the drag view
2353 // back into position
2354 final Runnable onCompleteRunnable = new Runnable() {
2355 @Override
2356 public void run() {
2357 onEndReordering();
2358 }
2359 };
2360 if (!mDeferringForDelete) {
2361 mPostReorderingPreZoomInRunnable = new Runnable() {
2362 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002363 onCompleteRunnable.run();
2364 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002365 };
2366 };
2367
2368 mPostReorderingPreZoomInRemainingAnimationCount =
2369 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2370 // Snap to the current page
2371 snapToPage(indexOfChild(mDragView), 0);
2372 // Animate the drag view back to the front position
2373 animateDragViewToOriginalPosition();
2374 } else {
2375 // Handled in post-delete-animation-callbacks
2376 }
2377 }
2378
Adam Cohen7d30a372013-07-01 17:03:59 -07002379 /*
2380 * Flinging to delete - IN PROGRESS
2381 */
2382 private PointF isFlingingToDelete() {
2383 ViewConfiguration config = ViewConfiguration.get(getContext());
2384 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2385
2386 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2387 // Do a quick dot product test to ensure that we are flinging upwards
2388 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2389 mVelocityTracker.getYVelocity());
2390 PointF upVec = new PointF(0f, -1f);
2391 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2392 (vel.length() * upVec.length()));
2393 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2394 return vel;
2395 }
2396 }
2397 return null;
2398 }
2399
2400 /**
2401 * Creates an animation from the current drag view along its current velocity vector.
2402 * For this animation, the alpha runs for a fixed duration and we update the position
2403 * progressively.
2404 */
2405 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2406 private View mDragView;
2407 private PointF mVelocity;
2408 private Rect mFrom;
2409 private long mPrevTime;
2410 private float mFriction;
2411
2412 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2413
2414 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2415 long startTime, float friction) {
2416 mDragView = dragView;
2417 mVelocity = vel;
2418 mFrom = from;
2419 mPrevTime = startTime;
2420 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2421 }
2422
2423 @Override
2424 public void onAnimationUpdate(ValueAnimator animation) {
2425 float t = ((Float) animation.getAnimatedValue()).floatValue();
2426 long curTime = AnimationUtils.currentAnimationTimeMillis();
2427
2428 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2429 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2430
2431 mDragView.setTranslationX(mFrom.left);
2432 mDragView.setTranslationY(mFrom.top);
2433 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2434
2435 mVelocity.x *= mFriction;
2436 mVelocity.y *= mFriction;
2437 mPrevTime = curTime;
2438 }
2439 };
2440
2441 private static final int ANIM_TAG_KEY = 100;
2442
2443 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2444 return new Runnable() {
2445 @Override
2446 public void run() {
2447 int dragViewIndex = indexOfChild(dragView);
2448
2449 // For each of the pages around the drag view, animate them from the previous
2450 // position to the new position in the layout (as a result of the drag view moving
2451 // in the layout)
2452 // NOTE: We can make an assumption here because we have side-bound pages that we
2453 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002454 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002455 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2456 boolean slideFromLeft = (isLastWidgetPage ||
2457 dragViewIndex > mTempVisiblePagesRange[0]);
2458
2459 // Setup the scroll to the correct page before we swap the views
2460 if (slideFromLeft) {
2461 snapToPageImmediately(dragViewIndex - 1);
2462 }
2463
2464 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2465 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2466 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2467 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2468 ArrayList<Animator> animations = new ArrayList<Animator>();
2469 for (int i = lowerIndex; i <= upperIndex; ++i) {
2470 View v = getChildAt(i);
2471 // dragViewIndex < pageUnderPointIndex, so after we remove the
2472 // drag view all subsequent views to pageUnderPointIndex will
2473 // shift down.
2474 int oldX = 0;
2475 int newX = 0;
2476 if (slideFromLeft) {
2477 if (i == 0) {
2478 // Simulate the page being offscreen with the page spacing
2479 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2480 - mPageSpacing;
2481 } else {
2482 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2483 }
2484 newX = getViewportOffsetX() + getChildOffset(i);
2485 } else {
2486 oldX = getChildOffset(i) - getChildOffset(i - 1);
2487 newX = 0;
2488 }
2489
2490 // Animate the view translation from its old position to its new
2491 // position
2492 AnimatorSet anim = (AnimatorSet) v.getTag();
2493 if (anim != null) {
2494 anim.cancel();
2495 }
2496
2497 // Note: Hacky, but we want to skip any optimizations to not draw completely
2498 // hidden views
2499 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2500 v.setTranslationX(oldX - newX);
2501 anim = new AnimatorSet();
2502 anim.playTogether(
2503 ObjectAnimator.ofFloat(v, "translationX", 0f),
2504 ObjectAnimator.ofFloat(v, "alpha", 1f));
2505 animations.add(anim);
2506 v.setTag(ANIM_TAG_KEY, anim);
2507 }
2508
2509 AnimatorSet slideAnimations = new AnimatorSet();
2510 slideAnimations.playTogether(animations);
2511 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2512 slideAnimations.addListener(new AnimatorListenerAdapter() {
2513 @Override
2514 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002515 mDeferringForDelete = false;
2516 onEndReordering();
2517 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002518 }
2519 });
2520 slideAnimations.start();
2521
2522 removeView(dragView);
2523 onRemoveView(dragView, true);
2524 }
2525 };
2526 }
2527
2528 public void onFlingToDelete(PointF vel) {
2529 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2530
2531 // NOTE: Because it takes time for the first frame of animation to actually be
2532 // called and we expect the animation to be a continuation of the fling, we have
2533 // to account for the time that has elapsed since the fling finished. And since
2534 // we don't have a startDelay, we will always get call to update when we call
2535 // start() (which we want to ignore).
2536 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2537 private int mCount = -1;
2538 private long mStartTime;
2539 private float mOffset;
2540 /* Anonymous inner class ctor */ {
2541 mStartTime = startTime;
2542 }
2543
2544 @Override
2545 public float getInterpolation(float t) {
2546 if (mCount < 0) {
2547 mCount++;
2548 } else if (mCount == 0) {
2549 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2550 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2551 mCount++;
2552 }
2553 return Math.min(1f, mOffset + t);
2554 }
2555 };
2556
2557 final Rect from = new Rect();
2558 final View dragView = mDragView;
2559 from.left = (int) dragView.getTranslationX();
2560 from.top = (int) dragView.getTranslationY();
2561 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2562 from, startTime, FLING_TO_DELETE_FRICTION);
2563
2564 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2565
2566 // Create and start the animation
2567 ValueAnimator mDropAnim = new ValueAnimator();
2568 mDropAnim.setInterpolator(tInterpolator);
2569 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2570 mDropAnim.setFloatValues(0f, 1f);
2571 mDropAnim.addUpdateListener(updateCb);
2572 mDropAnim.addListener(new AnimatorListenerAdapter() {
2573 public void onAnimationEnd(Animator animation) {
2574 onAnimationEndRunnable.run();
2575 }
2576 });
2577 mDropAnim.start();
2578 mDeferringForDelete = true;
2579 }
2580
2581 /* Drag to delete */
2582 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2583 if (mDeleteDropTarget != null) {
2584 mAltTmpRect.set(0, 0, 0, 0);
2585 View parent = (View) mDeleteDropTarget.getParent();
2586 if (parent != null) {
2587 parent.getGlobalVisibleRect(mAltTmpRect);
2588 }
2589 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2590 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2591 return mTmpRect.contains(x, y);
2592 }
2593 return false;
2594 }
2595
2596 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2597
2598 private void onDropToDelete() {
2599 final View dragView = mDragView;
2600
2601 final float toScale = 0f;
2602 final float toAlpha = 0f;
2603
2604 // Create and start the complex animation
2605 ArrayList<Animator> animations = new ArrayList<Animator>();
2606 AnimatorSet motionAnim = new AnimatorSet();
2607 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2608 motionAnim.playTogether(
2609 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2610 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2611 animations.add(motionAnim);
2612
2613 AnimatorSet alphaAnim = new AnimatorSet();
2614 alphaAnim.setInterpolator(new LinearInterpolator());
2615 alphaAnim.playTogether(
2616 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2617 animations.add(alphaAnim);
2618
2619 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2620
2621 AnimatorSet anim = new AnimatorSet();
2622 anim.playTogether(animations);
2623 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2624 anim.addListener(new AnimatorListenerAdapter() {
2625 public void onAnimationEnd(Animator animation) {
2626 onAnimationEndRunnable.run();
2627 }
2628 });
2629 anim.start();
2630
2631 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002632 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002633
2634 /* Accessibility */
2635 @Override
2636 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2637 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002638 info.setScrollable(getPageCount() > 1);
2639 if (getCurrentPage() < getPageCount() - 1) {
2640 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2641 }
2642 if (getCurrentPage() > 0) {
2643 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2644 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002645 }
2646
2647 @Override
2648 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2649 super.onInitializeAccessibilityEvent(event);
2650 event.setScrollable(true);
2651 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2652 event.setFromIndex(mCurrentPage);
2653 event.setToIndex(mCurrentPage);
2654 event.setItemCount(getChildCount());
2655 }
2656 }
2657
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002658 @Override
2659 public boolean performAccessibilityAction(int action, Bundle arguments) {
2660 if (super.performAccessibilityAction(action, arguments)) {
2661 return true;
2662 }
2663 switch (action) {
2664 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2665 if (getCurrentPage() < getPageCount() - 1) {
2666 scrollRight();
2667 return true;
2668 }
2669 } break;
2670 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2671 if (getCurrentPage() > 0) {
2672 scrollLeft();
2673 return true;
2674 }
2675 } break;
2676 }
2677 return false;
2678 }
2679
Adam Cohen0ffac432013-07-10 11:19:26 -07002680 protected String getCurrentPageDescription() {
2681 return String.format(getContext().getString(R.string.default_scroll_format),
2682 getNextPage() + 1, getChildCount());
2683 }
2684
Winson Chungd11265e2011-08-30 13:37:23 -07002685 @Override
2686 public boolean onHoverEvent(android.view.MotionEvent event) {
2687 return true;
2688 }
Adam Cohenf358a4b2013-07-23 16:47:31 -07002689}