blob: 9bdbe4665e65e18ce0d1b141115cbb81087418fe [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen7d30a372013-07-01 17:03:59 -070027import android.content.res.Resources;
Adam Cohen9c4949e2010-10-05 12:27:22 -070028import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070029import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070030import android.graphics.Matrix;
31import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070032import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070033import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070034import android.os.Parcel;
35import android.os.Parcelable;
36import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070037import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070038import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080039import android.view.InputDevice;
40import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070041import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewGroup;
46import android.view.ViewParent;
Adam Cohen96d30a12013-07-16 18:13:21 -070047import android.view.ViewGroup.LayoutParams;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070049import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070050import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070051import android.view.animation.AnimationUtils;
52import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080053import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070054import android.view.animation.LinearInterpolator;
Adam Cohen96d30a12013-07-16 18:13:21 -070055import android.widget.FrameLayout;
Winson Chung321e9ee2010-08-09 13:37:56 -070056import android.widget.Scroller;
57
Winson Chung6a0f57d2011-06-29 20:10:49 -070058import java.util.ArrayList;
59
Winson Chung321e9ee2010-08-09 13:37:56 -070060/**
61 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070062 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070063 */
Michael Jurka8b805b12012-04-18 14:23:14 -070064public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070065 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070066 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070067 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070068
Winson Chung86f77532010-08-24 11:08:22 -070069 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070070 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070071
Adam Cohen7d30a372013-07-01 17:03:59 -070072 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070073 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070074 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070075
Adam Cohenb5ba0972011-09-07 18:02:31 -070076 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070077 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080078
Adam Cohenb64cb5a2011-02-15 13:53:42 -080079 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080080 // The page is moved more than halfway, automatically move to the next page on touch up.
81 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080082
Adam Cohen265b9a62011-12-07 14:37:18 -080083 // The following constants need to be scaled based on density. The scaled versions will be
84 // assigned to the corresponding member variables below.
85 private static final int FLING_THRESHOLD_VELOCITY = 500;
86 private static final int MIN_SNAP_VELOCITY = 1500;
87 private static final int MIN_FLING_VELOCITY = 250;
88
Adam Cohen7d30a372013-07-01 17:03:59 -070089 // We are disabling touch interaction of the widget region for factory ROM.
90 private static final boolean DISABLE_TOUCH_INTERACTION = false;
91 private static final boolean DISABLE_TOUCH_SIDE_PAGES = false;
Adam Cohendedbd962013-07-11 14:21:49 -070092 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070093
Winson Chung8aad6102012-05-11 16:27:49 -070094 static final int AUTOMATIC_PAGE_SPACING = -1;
95
Adam Cohen265b9a62011-12-07 14:37:18 -080096 protected int mFlingThresholdVelocity;
97 protected int mMinFlingVelocity;
98 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -070099
Adam Cohenb5ba0972011-09-07 18:02:31 -0700100 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700101 protected float mSmoothingTime;
102 protected float mTouchX;
103
104 protected boolean mFirstLayout = true;
105
106 protected int mCurrentPage;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700107 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700108
Michael Jurka0142d492010-08-25 17:46:15 -0700109 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800110 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700111 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700112 private VelocityTracker mVelocityTracker;
113
Adam Cohen7d30a372013-07-01 17:03:59 -0700114 private float mParentDownMotionX;
115 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700116 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700117 private float mDownMotionY;
118 private float mDownScrollX;
Michael Jurka7426c422010-11-11 15:23:47 -0800119 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800120 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800121 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800122 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700123 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700124
125 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700126
Michael Jurka0142d492010-08-25 17:46:15 -0700127 protected final static int TOUCH_STATE_REST = 0;
128 protected final static int TOUCH_STATE_SCROLLING = 1;
129 protected final static int TOUCH_STATE_PREV_PAGE = 2;
130 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700131 protected final static int TOUCH_STATE_REORDERING = 4;
132
Adam Cohene45440e2010-10-14 18:33:38 -0700133 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700134
Michael Jurka0142d492010-08-25 17:46:15 -0700135 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700136 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700137
Michael Jurka0142d492010-08-25 17:46:15 -0700138 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700139
Michael Jurka7426c422010-11-11 15:23:47 -0800140 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700141 private int mPagingTouchSlop;
142 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700143 protected int mPageSpacing;
144 protected int mPageLayoutPaddingTop;
145 protected int mPageLayoutPaddingBottom;
146 protected int mPageLayoutPaddingLeft;
147 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700148 protected int mPageLayoutWidthGap;
149 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700150 protected int mCellCountX = 0;
151 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700152 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800153 protected boolean mAllowOverScroll = true;
154 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800155 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700156 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700157
Michael Jurka8b805b12012-04-18 14:23:14 -0700158 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800159 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
160 // the screens from continuing to translate beyond the normal bounds.
161 protected int mOverScrollX;
162
Michael Jurka5f1c5092010-09-03 14:15:02 -0700163 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700164
Michael Jurka5f1c5092010-09-03 14:15:02 -0700165 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700166
Winson Chung86f77532010-08-24 11:08:22 -0700167 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700168
Michael Jurkae326f182011-11-21 14:05:46 -0800169 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700170
Michael Jurka0142d492010-08-25 17:46:15 -0700171 // If true, syncPages and syncPageItems will be called to refresh pages
172 protected boolean mContentIsRefreshable = true;
173
174 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700175 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700176
177 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
178 // to switch to a new page
179 protected boolean mUsePagingTouchSlop = true;
180
Michael Jurka8b805b12012-04-18 14:23:14 -0700181 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700182 // (SmoothPagedView does this)
183 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700184 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700185
Patrick Dubroy1262e362010-10-06 15:49:50 -0700186 protected boolean mIsPageMoving = false;
187
Winson Chungf0ea4d32011-06-06 14:27:16 -0700188 // All syncs and layout passes are deferred until data is ready.
189 protected boolean mIsDataReady = false;
190
Adam Cohen7d30a372013-07-01 17:03:59 -0700191 protected boolean mAllowLongPress = true;
192
Winson Chungd2be3812013-07-16 11:11:32 -0700193 // Page Indicator
194 private int mPageIndicatorViewId;
195 private PageIndicator mPageIndicator;
Winson Chung007c6982011-06-14 13:27:53 -0700196
Adam Cohen7d30a372013-07-01 17:03:59 -0700197 // The viewport whether the pages are to be contained (the actual view may be larger than the
198 // viewport)
199 private Rect mViewport = new Rect();
200
201 // Reordering
202 // We use the min scale to determine how much to expand the actually PagedView measured
203 // dimensions such that when we are zoomed out, the view is not clipped
204 private int REORDERING_DROP_REPOSITION_DURATION = 200;
205 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
206 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
207 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 300;
208 private float REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE = 0.1f;
209 private long REORDERING_DELETE_DROP_TARGET_FADE_DURATION = 150;
210 private float mMinScale = 1f;
211 protected View mDragView;
212 protected AnimatorSet mZoomInOutAnim;
213 private Runnable mSidePageHoverRunnable;
214 private int mSidePageHoverIndex = -1;
215 // This variable's scope is only for the duration of startReordering() and endReordering()
216 private boolean mReorderingStarted = false;
217 // This variable's scope is for the duration of startReordering() and after the zoomIn()
218 // animation after endReordering()
219 private boolean mIsReordering;
220 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
221 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
222 private int mPostReorderingPreZoomInRemainingAnimationCount;
223 private Runnable mPostReorderingPreZoomInRunnable;
224
225 // Edge swiping
226 private boolean mOnlyAllowEdgeSwipes = false;
227 private boolean mDownEventOnEdge = false;
228 private int mEdgeSwipeRegionSize = 0;
229
230 // Convenience/caching
231 private Matrix mTmpInvMatrix = new Matrix();
232 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700233 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700234 private Rect mTmpRect = new Rect();
235 private Rect mAltTmpRect = new Rect();
236
237 // Fling to delete
238 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
239 private float FLING_TO_DELETE_FRICTION = 0.035f;
240 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
241 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
242 protected int mFlingToDeleteThresholdVelocity = -1400;
243 // Drag to delete
244 private boolean mDeferringForDelete = false;
245 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
246 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
247
248 // Drop to delete
249 private View mDeleteDropTarget;
250
251 private boolean mAutoComputePageSpacing = false;
252 private boolean mRecomputePageSpacing = false;
253
254 // Bouncer
255 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700256
Winson Chung86f77532010-08-24 11:08:22 -0700257 public interface PageSwitchListener {
258 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700259 }
260
Winson Chung321e9ee2010-08-09 13:37:56 -0700261 public PagedView(Context context) {
262 this(context, null);
263 }
264
265 public PagedView(Context context, AttributeSet attrs) {
266 this(context, attrs, 0);
267 }
268
269 public PagedView(Context context, AttributeSet attrs, int defStyle) {
270 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700271
Adam Cohen9c4949e2010-10-05 12:27:22 -0700272 TypedArray a = context.obtainStyledAttributes(attrs,
273 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800274 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700275 if (mPageSpacing < 0) {
276 mAutoComputePageSpacing = mRecomputePageSpacing = true;
277 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700278 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800279 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700280 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800281 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700282 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800283 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700284 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800285 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700286 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700287 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700288 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700289 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700290 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700291 a.recycle();
292
Winson Chung321e9ee2010-08-09 13:37:56 -0700293 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700294 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700295 }
296
297 /**
298 * Initializes various states for this workspace.
299 */
Michael Jurka0142d492010-08-25 17:46:15 -0700300 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700301 mDirtyPageContent = new ArrayList<Boolean>();
302 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800303 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700304 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700305 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700306
307 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700308 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700309 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
310 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700311 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800312
Adam Cohen7d30a372013-07-01 17:03:59 -0700313 // Scale the fling-to-delete threshold by the density
314 mFlingToDeleteThresholdVelocity =
315 (int) (mFlingToDeleteThresholdVelocity * mDensity);
316
Adam Cohen265b9a62011-12-07 14:37:18 -0800317 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
318 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
319 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700320 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700321 }
322
Winson Chungd2be3812013-07-16 11:11:32 -0700323 protected void onAttachedToWindow() {
324 // Hook up the page indicator
325 ViewGroup parent = (ViewGroup) getParent();
326 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
327 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
328 mPageIndicator.removeAllMarkers();
Winson Chung82dfe582013-07-26 15:07:49 -0700329
330 ArrayList<Integer> markers = new ArrayList<Integer>();
331 for (int i = 0; i < getChildCount(); ++i) {
332 markers.add(getPageIndicatorMarker(i));
333 }
334 mPageIndicator.addMarkers(markers);
Winson Chungd2be3812013-07-16 11:11:32 -0700335 }
336 }
337
338 protected void onDetachedFromWindow() {
339 // Unhook the page indicator
340 mPageIndicator = null;
341 }
342
Adam Cohen7d30a372013-07-01 17:03:59 -0700343 void setDeleteDropTarget(View v) {
344 mDeleteDropTarget = v;
345 }
346
347 // Convenience methods to map points from self to parent and vice versa
348 float[] mapPointFromViewToParent(View v, float x, float y) {
349 mTmpPoint[0] = x;
350 mTmpPoint[1] = y;
351 v.getMatrix().mapPoints(mTmpPoint);
352 mTmpPoint[0] += v.getLeft();
353 mTmpPoint[1] += v.getTop();
354 return mTmpPoint;
355 }
356 float[] mapPointFromParentToView(View v, float x, float y) {
357 mTmpPoint[0] = x - v.getLeft();
358 mTmpPoint[1] = y - v.getTop();
359 v.getMatrix().invert(mTmpInvMatrix);
360 mTmpInvMatrix.mapPoints(mTmpPoint);
361 return mTmpPoint;
362 }
363
364 void updateDragViewTranslationDuringDrag() {
365 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
366 float y = mLastMotionY - mDownMotionY;
367 mDragView.setTranslationX(x);
368 mDragView.setTranslationY(y);
369
370 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
371 }
372
373 public void setMinScale(float f) {
374 mMinScale = f;
375 requestLayout();
376 }
377
378 @Override
379 public void setScaleX(float scaleX) {
380 super.setScaleX(scaleX);
381 if (isReordering(true)) {
382 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
383 mLastMotionX = p[0];
384 mLastMotionY = p[1];
385 updateDragViewTranslationDuringDrag();
386 }
387 }
388
389 // Convenience methods to get the actual width/height of the PagedView (since it is measured
390 // to be larger to account for the minimum possible scale)
391 int getViewportWidth() {
392 return mViewport.width();
393 }
394 int getViewportHeight() {
395 return mViewport.height();
396 }
397
398 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
399 // PagedView both horizontally and vertically
400 int getViewportOffsetX() {
401 return (getMeasuredWidth() - getViewportWidth()) / 2;
402 }
403
404 int getViewportOffsetY() {
405 return (getMeasuredHeight() - getViewportHeight()) / 2;
406 }
407
Adam Cohenedb40762013-07-18 16:45:45 -0700408 PageIndicator getPageIndicator() {
409 return mPageIndicator;
410 }
Winson Chung82dfe582013-07-26 15:07:49 -0700411 protected int getPageIndicatorMarker(int pageIndex) {
412 return R.layout.page_indicator_marker;
413 }
Adam Cohenedb40762013-07-18 16:45:45 -0700414
Winson Chung86f77532010-08-24 11:08:22 -0700415 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
416 mPageSwitchListener = pageSwitchListener;
417 if (mPageSwitchListener != null) {
418 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700419 }
420 }
421
422 /**
Winson Chung52aee602013-01-30 12:01:02 -0800423 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
424 */
425 public boolean isLayoutRtl() {
426 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
427 }
428
429 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700430 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
431 * out pages.
432 */
433 protected void setDataIsReady() {
434 mIsDataReady = true;
435 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700436
Winson Chungf0ea4d32011-06-06 14:27:16 -0700437 protected boolean isDataReady() {
438 return mIsDataReady;
439 }
440
441 /**
Winson Chung86f77532010-08-24 11:08:22 -0700442 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700443 *
Winson Chung86f77532010-08-24 11:08:22 -0700444 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700445 */
Winson Chung86f77532010-08-24 11:08:22 -0700446 int getCurrentPage() {
447 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700448 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700449
Winson Chung360e63f2012-04-27 13:48:05 -0700450 int getNextPage() {
451 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
452 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700453
Winson Chung86f77532010-08-24 11:08:22 -0700454 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700455 return getChildCount();
456 }
457
Winson Chung86f77532010-08-24 11:08:22 -0700458 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700459 return getChildAt(index);
460 }
461
Adam Cohenae4f1552011-10-20 00:15:42 -0700462 protected int indexToPage(int index) {
463 return index;
464 }
465
Winson Chung321e9ee2010-08-09 13:37:56 -0700466 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800467 * Updates the scroll of the current page immediately to its final scroll position. We use this
468 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
469 * the previous tab page.
470 */
471 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700472 // If the current page is invalid, just reset the scroll position to zero
473 int newX = 0;
474 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700475 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700476 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800477 scrollTo(newX, 0);
478 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800479 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800480 }
481
482 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700483 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
484 * ends, {@link #resumeScrolling()} should be called, along with
485 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
486 */
487 void pauseScrolling() {
488 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700489 }
490
491 /**
492 * Enables scrolling again.
493 * @see #pauseScrolling()
494 */
495 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700496 }
497 /**
Winson Chung86f77532010-08-24 11:08:22 -0700498 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700499 */
Winson Chung86f77532010-08-24 11:08:22 -0700500 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800501 if (!mScroller.isFinished()) {
502 mScroller.abortAnimation();
503 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800504 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
505 // the default
506 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800507 return;
508 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700509
Adam Cohene61a9a22013-06-11 15:45:31 -0700510 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700511 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700512 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700513 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800514 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700515 }
516
Michael Jurka0142d492010-08-25 17:46:15 -0700517 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700518 if (mPageSwitchListener != null) {
519 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700520 }
Winson Chungd2be3812013-07-16 11:11:32 -0700521
522 // Update the page indicator (when we aren't reordering)
523 if (mPageIndicator != null && !isReordering(false)) {
524 mPageIndicator.setActiveMarker(getNextPage());
525 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700526 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800527 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700528 if (!mIsPageMoving) {
529 mIsPageMoving = true;
530 onPageBeginMoving();
531 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700532 }
533
Michael Jurkace7e05f2011-02-01 22:02:35 -0800534 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700535 if (mIsPageMoving) {
536 mIsPageMoving = false;
537 onPageEndMoving();
538 }
Michael Jurka0142d492010-08-25 17:46:15 -0700539 }
540
Adam Cohen26976d92011-03-22 15:33:33 -0700541 protected boolean isPageMoving() {
542 return mIsPageMoving;
543 }
544
Michael Jurka0142d492010-08-25 17:46:15 -0700545 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700546 protected void onPageBeginMoving() {
547 }
548
549 // a method that subclasses can override to add behavior
550 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700551 }
552
Winson Chung321e9ee2010-08-09 13:37:56 -0700553 /**
Winson Chung86f77532010-08-24 11:08:22 -0700554 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700555 *
556 * @param l The listener used to respond to long clicks.
557 */
558 @Override
559 public void setOnLongClickListener(OnLongClickListener l) {
560 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700561 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700562 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700563 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700564 }
565 }
566
567 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800568 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700569 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800570 }
571
572 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700573 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700574 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800575 mUnboundedScrollX = x;
576
Adam Cohen0ffac432013-07-10 11:19:26 -0700577 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
578 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
579 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800580 super.scrollTo(0, y);
581 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700582 if (isRtl) {
583 overScroll(x - mMaxScrollX);
584 } else {
585 overScroll(x);
586 }
Adam Cohen68d73932010-11-15 10:50:58 -0800587 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700588 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800589 super.scrollTo(mMaxScrollX, y);
590 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700591 if (isRtl) {
592 overScroll(x);
593 } else {
594 overScroll(x - mMaxScrollX);
595 }
Adam Cohen68d73932010-11-15 10:50:58 -0800596 }
597 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800598 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800599 super.scrollTo(x, y);
600 }
601
Michael Jurka0142d492010-08-25 17:46:15 -0700602 mTouchX = x;
603 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700604
605 // Update the last motion events when scrolling
606 if (isReordering(true)) {
607 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
608 mLastMotionX = p[0];
609 mLastMotionY = p[1];
610 updateDragViewTranslationDuringDrag();
611 }
Michael Jurka0142d492010-08-25 17:46:15 -0700612 }
613
614 // we moved this functionality to a helper function so SmoothPagedView can reuse it
615 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700616 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700617 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700618 if (getScrollX() != mScroller.getCurrX()
619 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700620 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700621 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
622 }
Michael Jurka0142d492010-08-25 17:46:15 -0700623 invalidate();
624 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700625 } else if (mNextPage != INVALID_PAGE) {
626 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700627 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700628 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700629
Winson Chung9c0565f2013-07-19 13:49:06 -0700630 // Load the associated pages if necessary
631 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
632 loadAssociatedPages(mCurrentPage);
633 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
634 }
635
Adam Cohen73aa9752010-11-24 16:26:58 -0800636 // We don't want to trigger a page end moving unless the page has settled
637 // and the user has stopped scrolling
638 if (mTouchState == TOUCH_STATE_REST) {
639 pageEndMoving();
640 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700641
Adam Cohen7d30a372013-07-01 17:03:59 -0700642 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700643 // Notify the user when the page changes
644 AccessibilityManager accessibilityManager = (AccessibilityManager)
645 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
646 if (accessibilityManager.isEnabled()) {
647 AccessibilityEvent ev =
648 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
649 ev.getText().add(getCurrentPageDescription());
650 sendAccessibilityEventUnchecked(ev);
651 }
Michael Jurka0142d492010-08-25 17:46:15 -0700652 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700653 }
Michael Jurka0142d492010-08-25 17:46:15 -0700654 return false;
655 }
656
657 @Override
658 public void computeScroll() {
659 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700660 }
661
Adam Cohen7d30a372013-07-01 17:03:59 -0700662 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
663 return mTopAlignPageWhenShrinkingForBouncer;
664 }
665
Adam Cohen96d30a12013-07-16 18:13:21 -0700666 public static class LayoutParams extends ViewGroup.LayoutParams {
667 public boolean isFullScreenPage = false;
668
669 /**
670 * {@inheritDoc}
671 */
672 public LayoutParams(int width, int height) {
673 super(width, height);
674 }
675
676 public LayoutParams(ViewGroup.LayoutParams source) {
677 super(source);
678 }
679 }
680
681 protected LayoutParams generateDefaultLayoutParams() {
682 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
683 }
684
Adam Cohenedb40762013-07-18 16:45:45 -0700685 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700686 LayoutParams lp = generateDefaultLayoutParams();
687 lp.isFullScreenPage = true;
688 super.addView(page, 0, lp);
689 }
690
Winson Chung321e9ee2010-08-09 13:37:56 -0700691 @Override
692 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700693 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700694 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
695 return;
696 }
697
Adam Cohen7d30a372013-07-01 17:03:59 -0700698 // We measure the dimensions of the PagedView to be larger than the pages so that when we
699 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700700 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
701 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
702 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700703 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700704 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
705 // viewport, we can be at most one and a half screens offset once we scale down
706 DisplayMetrics dm = getResources().getDisplayMetrics();
707 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
708 int parentWidthSize = (int) (1.5f * maxSize);
709 int parentHeightSize = maxSize;
710 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
711 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
712 mViewport.set(0, 0, widthSize, heightSize);
713
714 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
715 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
716 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700717 }
718
Winson Chung8aad6102012-05-11 16:27:49 -0700719 // Return early if we aren't given a proper dimension
720 if (widthSize <= 0 || heightSize <= 0) {
721 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
722 return;
723 }
724
Adam Lesinski6b879f02010-11-04 16:15:23 -0700725 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
726 * of the All apps view on XLarge displays to not take up more space then it needs. Width
727 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
728 * each page to have the same width.
729 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700730 final int verticalPadding = getPaddingTop() + getPaddingBottom();
731 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700732
733 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700734 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700735 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700736 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
737 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
738 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
739 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700740 final int childCount = getChildCount();
741 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700742 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700743 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700744 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
745
746 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700747 int childHeightMode;
748 int childWidth;
749 int childHeight;
750
751 if (!lp.isFullScreenPage) {
752 if (lp.width == LayoutParams.WRAP_CONTENT) {
753 childWidthMode = MeasureSpec.AT_MOST;
754 } else {
755 childWidthMode = MeasureSpec.EXACTLY;
756 }
757
758 if (lp.height == LayoutParams.WRAP_CONTENT) {
759 childHeightMode = MeasureSpec.AT_MOST;
760 } else {
761 childHeightMode = MeasureSpec.EXACTLY;
762 }
763
764 childWidth = widthSize - horizontalPadding;
765 childHeight = heightSize - verticalPadding;
766
Michael Jurka5f1c5092010-09-03 14:15:02 -0700767 } else {
768 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700769 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700770
771 childWidth = getViewportWidth();
772 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700773 }
774
775 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700776 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
777 final int childHeightMeasureSpec =
778 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700779 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700780 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700781 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700782
Winson Chunga128a7b2012-04-30 15:23:15 -0700783 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700784 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700785 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700786 // The gap between pages in the PagedView should be equal to the gap from the page
787 // to the edge of the screen (so it is not visible in the current screen). To
788 // account for unequal padding on each side of the paged view, we take the maximum
789 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700790 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700791 int spacing = Math.max(offset, widthSize - offset -
792 getChildAt(0).getMeasuredWidth());
793 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700794 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700795 }
796 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700797 }
798
Adam Cohen60b07122011-11-14 17:26:06 -0800799 public void setPageSpacing(int pageSpacing) {
800 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700801 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800802 }
803
Winson Chung321e9ee2010-08-09 13:37:56 -0700804 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700805 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700806 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700807 return;
808 }
809
Winson Chung785d2eb2011-04-14 16:08:02 -0700810 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700811 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700812
Adam Cohenedb40762013-07-18 16:45:45 -0700813 int screenWidth = getViewportWidth();
814
Adam Cohen7d30a372013-07-01 17:03:59 -0700815 int offsetX = getViewportOffsetX();
816 int offsetY = getViewportOffsetY();
817
818 // Update the viewport offsets
819 mViewport.offset(offsetX, offsetY);
820
Adam Cohen0ffac432013-07-10 11:19:26 -0700821 final boolean isRtl = isLayoutRtl();
822
823 final int startIndex = isRtl ? childCount - 1 : 0;
824 final int endIndex = isRtl ? -1 : childCount;
825 final int delta = isRtl ? -1 : 1;
826
Adam Cohen7d30a372013-07-01 17:03:59 -0700827 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700828 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
829
830 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
831 mPageScrolls = new int[getChildCount()];
832 }
833
Adam Cohen0ffac432013-07-10 11:19:26 -0700834 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700835 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700836 LayoutParams lp = (LayoutParams) child.getLayoutParams();
837 int childTop;
838
839 if (lp.isFullScreenPage) {
840 childTop = offsetY;
841 } else {
842 childTop = offsetY + getPaddingTop();
843 if (mCenterPagesVertically) {
844 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
845 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700846 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700847
Winson Chung321e9ee2010-08-09 13:37:56 -0700848 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700849 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700850 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800851
Winson Chung785d2eb2011-04-14 16:08:02 -0700852 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700853 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800854 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700855
856 // We assume the left and right padding are equal, and hence center the pages
857 // horizontally
858 int scrollOffset = false ? 0 : (getViewportWidth() - childWidth) / 2;
859 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
860
Adam Cohen9c4949e2010-10-05 12:27:22 -0700861 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700862 }
863 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700864
865 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
866 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800867 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700868 setHorizontalScrollBarEnabled(true);
869 mFirstLayout = false;
870 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700871
872 if (childCount > 0) {
873 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700874 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700875 } else {
876 mMaxScrollX = 0;
877 }
878
879 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
880 !mDeferringForDelete) {
881 setCurrentPage(getNextPage());
882 }
883 mChildCountOnLastLayout = getChildCount();
Winson Chunge3193b92010-09-10 11:44:42 -0700884 }
885
Adam Cohenf34bab52010-09-30 14:11:56 -0700886 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700887 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
888
889 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700890 for (int i = 0; i < getChildCount(); i++) {
891 View child = getChildAt(i);
892 if (child != null) {
893 float scrollProgress = getScrollProgress(screenCenter, child, i);
894 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800895 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700896 }
897 }
898 invalidate();
899 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700900 }
901
Winson Chunge3193b92010-09-10 11:44:42 -0700902 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700903 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700904 // Update the page indicator, we don't update the page indicator as we
905 // add/remove pages
906 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700907 int pageIndex = indexOfChild(child);
908 mPageIndicator.addMarker(pageIndex, getPageIndicatorMarker(pageIndex));
Winson Chungd2be3812013-07-16 11:11:32 -0700909 }
910
Adam Cohen2591f6a2011-10-25 14:36:40 -0700911 // This ensures that when children are added, they get the correct transforms / alphas
912 // in accordance with any scroll effects.
913 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700914 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700915
Adam Cohen2591f6a2011-10-25 14:36:40 -0700916 invalidate();
917 }
918
Michael Jurka8b805b12012-04-18 14:23:14 -0700919 @Override
920 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700921 mForceScreenScrolled = true;
922 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700923 }
924
Winson Chungd2be3812013-07-16 11:11:32 -0700925 private void removeMarkerForView(int index) {
926 // Update the page indicator, we don't update the page indicator as we
927 // add/remove pages
928 if (mPageIndicator != null && !isReordering(false)) {
929 mPageIndicator.removeMarker(index);
930 }
931 }
932
933 @Override
934 public void removeView(View v) {
935 // XXX: We should find a better way to hook into this before the view
936 // gets removed form its parent...
937 removeMarkerForView(indexOfChild(v));
938 super.removeView(v);
939 }
940 @Override
941 public void removeViewInLayout(View v) {
942 // XXX: We should find a better way to hook into this before the view
943 // gets removed form its parent...
944 removeMarkerForView(indexOfChild(v));
945 super.removeViewInLayout(v);
946 }
947 @Override
948 public void removeViewAt(int index) {
949 // XXX: We should find a better way to hook into this before the view
950 // gets removed form its parent...
951 removeViewAt(index);
952 super.removeViewAt(index);
953 }
954 @Override
955 public void removeAllViewsInLayout() {
956 // Update the page indicator, we don't update the page indicator as we
957 // add/remove pages
958 if (mPageIndicator != null) {
959 mPageIndicator.removeAllMarkers();
960 }
961
962 super.removeAllViewsInLayout();
963 }
964
Adam Cohen73894962011-10-31 13:17:17 -0700965 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700966 if (index < 0 || index > getChildCount() - 1) return 0;
967
Adam Cohen0ffac432013-07-10 11:19:26 -0700968 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700969
Adam Cohenf698c6e2013-07-17 18:44:25 -0700970 if (isRtl) index = getChildCount() - index - 1;
971 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -0700972
Adam Cohenf698c6e2013-07-17 18:44:25 -0700973 return offset;
Adam Cohen73894962011-10-31 13:17:17 -0700974 }
975
Winson Chungc9ca2982013-07-19 12:07:38 -0700976 void getReorderablePages(int[] range) {
977 range[0] = 0;
978 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -0700979 }
980
Michael Jurkadde558b2011-11-09 22:09:06 -0800981 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -0700982 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -0700983 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -0700984
Michael Jurkac4fb9172010-09-02 17:19:20 -0700985 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -0700986 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -0700987 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -0700988 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -0700989
Winson Chungc9ca2982013-07-19 12:07:38 -0700990 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
991 View currPage = getPageAt(leftScreen);
992
993 // Check if the right edge of the page is in the viewport
994 mTmpIntPoint[0] = currPage.getMeasuredWidth();
995 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
996 if (mTmpIntPoint[0] < 0) {
997 break;
998 }
999 }
1000 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1001 View currPage = getPageAt(rightScreen);
1002
1003 // Check if the left edge of the page is in the viewport
1004 mTmpIntPoint[0] = 0;
1005 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1006 if (mTmpIntPoint[0] >= viewportWidth) {
1007 break;
1008 }
1009 }
1010 range[0] = Math.max(0, leftScreen);
1011 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001012 } else {
1013 range[0] = -1;
1014 range[1] = -1;
1015 }
1016 }
1017
Michael Jurka920d7f42012-05-14 16:29:55 -07001018 protected boolean shouldDrawChild(View child) {
1019 return child.getAlpha() > 0;
1020 }
1021
Michael Jurkadde558b2011-11-09 22:09:06 -08001022 @Override
1023 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001024 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001025 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1026 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001027 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001028
1029 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001030 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1031 // set it for the next frame
1032 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001033 screenScrolled(screenCenter);
1034 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001035 }
1036
1037 // Find out which screens are visible; as an optimization we only call draw on them
1038 final int pageCount = getChildCount();
1039 if (pageCount > 0) {
1040 getVisiblePages(mTempVisiblePagesRange);
1041 final int leftScreen = mTempVisiblePagesRange[0];
1042 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001043 if (leftScreen != -1 && rightScreen != -1) {
1044 final long drawingTime = getDrawingTime();
1045 // Clip to the bounds
1046 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001047 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1048 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001049
Adam Cohen7d30a372013-07-01 17:03:59 -07001050 // Draw all the children, leaving the drag view for last
1051 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001052 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001053 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001054 if (mForceDrawAllChildrenNextFrame ||
1055 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001056 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001057 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001058 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001059 // Draw the drag view on top (if there is one)
1060 if (mDragView != null) {
1061 drawChild(canvas, mDragView, drawingTime);
1062 }
1063
Michael Jurka5e368ff2012-05-14 23:13:15 -07001064 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001065 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001066 }
Michael Jurka0142d492010-08-25 17:46:15 -07001067 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001068 }
1069
1070 @Override
1071 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001072 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001073 if (page != mCurrentPage || !mScroller.isFinished()) {
1074 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001075 return true;
1076 }
1077 return false;
1078 }
1079
1080 @Override
1081 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001082 int focusablePage;
1083 if (mNextPage != INVALID_PAGE) {
1084 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001085 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001086 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001087 }
Winson Chung86f77532010-08-24 11:08:22 -07001088 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001089 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001090 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001091 }
1092 return false;
1093 }
1094
1095 @Override
1096 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001097 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001098 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001099 if (getCurrentPage() > 0) {
1100 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001101 return true;
1102 }
1103 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001104 if (getCurrentPage() < getPageCount() - 1) {
1105 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001106 return true;
1107 }
1108 }
1109 return super.dispatchUnhandledMove(focused, direction);
1110 }
1111
1112 @Override
1113 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001114 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001115 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001116 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001117 }
1118 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001119 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001120 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001121 }
1122 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001123 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001124 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001125 }
1126 }
1127 }
1128
1129 /**
1130 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001131 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001132 *
Winson Chung86f77532010-08-24 11:08:22 -07001133 * This happens when live folders requery, and if they're off page, they
1134 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001135 */
1136 @Override
1137 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001138 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001139 View v = focused;
1140 while (true) {
1141 if (v == current) {
1142 super.focusableViewAvailable(focused);
1143 return;
1144 }
1145 if (v == this) {
1146 return;
1147 }
1148 ViewParent parent = v.getParent();
1149 if (parent instanceof View) {
1150 v = (View)v.getParent();
1151 } else {
1152 return;
1153 }
1154 }
1155 }
1156
1157 /**
1158 * {@inheritDoc}
1159 */
1160 @Override
1161 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1162 if (disallowIntercept) {
1163 // We need to make sure to cancel our long press if
1164 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001165 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001166 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001167 }
1168 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1169 }
1170
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001171 /**
1172 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1173 */
1174 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001175 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001176 if (isLayoutRtl()) {
1177 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001178 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001179 }
Adam Cohenedb40762013-07-18 16:45:45 -07001180 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001181 }
1182
1183 /**
1184 * Return true if a tap at (x, y) should trigger a flip to the next page.
1185 */
1186 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001187 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001188 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001189 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001190 }
1191 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001192 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001193 }
Winson Chung52aee602013-01-30 12:01:02 -08001194
Adam Cohen7d30a372013-07-01 17:03:59 -07001195 /** Returns whether x and y originated within the buffered viewport */
1196 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1197 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1198 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1199 return mTmpRect.contains(x, y);
1200 }
1201
1202 /** Returns whether x and y originated within the current page view bounds */
1203 private boolean isTouchPointInCurrentPage(int x, int y) {
1204 View v = getPageAt(getCurrentPage());
1205 if (v != null) {
1206 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1207 v.getBottom());
1208 return mTmpRect.contains(x, y);
1209 }
1210 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001211 }
1212
Winson Chung321e9ee2010-08-09 13:37:56 -07001213 @Override
1214 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001215 if (DISABLE_TOUCH_INTERACTION) {
1216 return false;
1217 }
1218
Winson Chung321e9ee2010-08-09 13:37:56 -07001219 /*
1220 * This method JUST determines whether we want to intercept the motion.
1221 * If we return true, onTouchEvent will be called and we do the actual
1222 * scrolling there.
1223 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001224 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001225
Winson Chung45e1d6e2010-11-09 17:19:49 -08001226 // Skip touch handling if there are no pages to swipe
1227 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1228
Winson Chung321e9ee2010-08-09 13:37:56 -07001229 /*
1230 * Shortcut the most recurring case: the user is in the dragging
1231 * state and he is moving his finger. We want to intercept this
1232 * motion.
1233 */
1234 final int action = ev.getAction();
1235 if ((action == MotionEvent.ACTION_MOVE) &&
1236 (mTouchState == TOUCH_STATE_SCROLLING)) {
1237 return true;
1238 }
1239
Winson Chung321e9ee2010-08-09 13:37:56 -07001240 switch (action & MotionEvent.ACTION_MASK) {
1241 case MotionEvent.ACTION_MOVE: {
1242 /*
1243 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1244 * whether the user has moved far enough from his original down touch.
1245 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001246 if (mActivePointerId != INVALID_POINTER) {
1247 determineScrollingStart(ev);
1248 break;
1249 }
1250 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1251 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1252 // i.e. fall through to the next case (don't break)
1253 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1254 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001255 }
1256
1257 case MotionEvent.ACTION_DOWN: {
1258 final float x = ev.getX();
1259 final float y = ev.getY();
1260 // Remember location of down touch
1261 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001262 mDownMotionY = y;
1263 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001264 mLastMotionX = x;
1265 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001266 float[] p = mapPointFromViewToParent(this, x, y);
1267 mParentDownMotionX = p[0];
1268 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001269 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001270 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001271 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001272
1273 // Determine if the down event is within the threshold to be an edge swipe
1274 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1275 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1276 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1277 mDownEventOnEdge = true;
1278 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001279
1280 /*
1281 * If being flinged and user touches the screen, initiate drag;
1282 * otherwise don't. mScroller.isFinished should be false when
1283 * being flinged.
1284 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001285 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001286 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1287 if (finishedScrolling) {
1288 mTouchState = TOUCH_STATE_REST;
1289 mScroller.abortAnimation();
1290 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001291 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1292 mTouchState = TOUCH_STATE_SCROLLING;
1293 } else {
1294 mTouchState = TOUCH_STATE_REST;
1295 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001296 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001297
Winson Chung86f77532010-08-24 11:08:22 -07001298 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001299 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001300 if (!DISABLE_TOUCH_SIDE_PAGES) {
1301 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1302 if (getChildCount() > 0) {
1303 if (hitsPreviousPage(x, y)) {
1304 mTouchState = TOUCH_STATE_PREV_PAGE;
1305 } else if (hitsNextPage(x, y)) {
1306 mTouchState = TOUCH_STATE_NEXT_PAGE;
1307 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001308 }
1309 }
1310 }
1311 break;
1312 }
1313
Winson Chung321e9ee2010-08-09 13:37:56 -07001314 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001315 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001316 resetTouchState();
1317 // Just intercept the touch event on up if we tap outside the strict viewport
1318 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1319 return true;
1320 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001321 break;
1322
1323 case MotionEvent.ACTION_POINTER_UP:
1324 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001325 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001326 break;
1327 }
1328
1329 /*
1330 * The only time we want to intercept motion events is if we are in the
1331 * drag mode.
1332 */
1333 return mTouchState != TOUCH_STATE_REST;
1334 }
1335
Adam Cohenf8d28232011-02-01 21:47:00 -08001336 protected void determineScrollingStart(MotionEvent ev) {
1337 determineScrollingStart(ev, 1.0f);
1338 }
1339
Winson Chung321e9ee2010-08-09 13:37:56 -07001340 /*
1341 * Determines if we should change the touch state to start scrolling after the
1342 * user moves their touch point too far.
1343 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001344 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001345 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001346 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001347 if (pointerIndex == -1) return;
1348
1349 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001350 final float x = ev.getX(pointerIndex);
1351 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001352 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1353
1354 // If we're only allowing edge swipes, we break out early if the down event wasn't
1355 // at the edge.
1356 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1357
Winson Chung321e9ee2010-08-09 13:37:56 -07001358 final int xDiff = (int) Math.abs(x - mLastMotionX);
1359 final int yDiff = (int) Math.abs(y - mLastMotionY);
1360
Adam Cohenf8d28232011-02-01 21:47:00 -08001361 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001362 boolean xPaged = xDiff > mPagingTouchSlop;
1363 boolean xMoved = xDiff > touchSlop;
1364 boolean yMoved = yDiff > touchSlop;
1365
Adam Cohenf8d28232011-02-01 21:47:00 -08001366 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001367 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001368 // Scroll if the user moved far enough along the X axis
1369 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001370 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001371 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001372 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001373 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001374 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1375 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001376 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001377 }
1378 }
1379
Adam Cohen7d30a372013-07-01 17:03:59 -07001380 protected float getMaxScrollProgress() {
1381 return 1.0f;
1382 }
1383
Adam Cohenf8d28232011-02-01 21:47:00 -08001384 protected void cancelCurrentPageLongPress() {
1385 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001386 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001387 // Try canceling the long press. It could also have been scheduled
1388 // by a distant descendant, so use the mAllowLongPress flag to block
1389 // everything
1390 final View currentPage = getPageAt(mCurrentPage);
1391 if (currentPage != null) {
1392 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001393 }
1394 }
1395 }
1396
Adam Cohen7d30a372013-07-01 17:03:59 -07001397 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1398 final int halfScreenSize = getViewportWidth() / 2;
1399
1400 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1401 screenCenter = Math.max(halfScreenSize, screenCenter);
1402
1403 return getScrollProgress(screenCenter, v, page);
1404 }
1405
Adam Cohenb5ba0972011-09-07 18:02:31 -07001406 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001407 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001408
Adam Cohen96d30a12013-07-16 18:13:21 -07001409 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001410 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001411
1412 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001413 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1414 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001415 return scrollProgress;
1416 }
1417
Adam Cohenedb40762013-07-18 16:45:45 -07001418 public int getScrollForPage(int index) {
1419 if (mPageScrolls == null || index >= mPageScrolls.length) {
1420 return 0;
1421 } else {
1422 return mPageScrolls[index];
1423 }
1424 }
1425
Adam Cohene0f66b52010-11-23 15:06:07 -08001426 // This curve determines how the effect of scrolling over the limits of the page dimishes
1427 // as the user pulls further and further from the bounds
1428 private float overScrollInfluenceCurve(float f) {
1429 f -= 1.0f;
1430 return f * f * f + 1.0f;
1431 }
1432
Adam Cohenb5ba0972011-09-07 18:02:31 -07001433 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001434 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001435
1436 // We want to reach the max over scroll effect when the user has
1437 // over scrolled half the size of the screen
1438 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1439
1440 if (f == 0) return;
1441
1442 // Clamp this factor, f, to -1 < f < 1
1443 if (Math.abs(f) >= 1) {
1444 f /= Math.abs(f);
1445 }
1446
1447 int overScrollAmount = (int) Math.round(f * screenSize);
1448 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001449 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001450 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001451 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001452 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001453 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001454 }
1455 invalidate();
1456 }
1457
1458 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001459 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001460
1461 float f = (amount / screenSize);
1462
1463 if (f == 0) return;
1464 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1465
Adam Cohen7bfc9792011-01-28 13:52:37 -08001466 // Clamp this factor, f, to -1 < f < 1
1467 if (Math.abs(f) >= 1) {
1468 f /= Math.abs(f);
1469 }
1470
Adam Cohene0f66b52010-11-23 15:06:07 -08001471 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001472 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001473 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001474 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001475 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001476 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001477 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001478 }
1479 invalidate();
1480 }
1481
Adam Cohenb5ba0972011-09-07 18:02:31 -07001482 protected void overScroll(float amount) {
1483 dampedOverScroll(amount);
1484 }
1485
Michael Jurkac5b262c2011-01-12 20:24:50 -08001486 protected float maxOverScroll() {
1487 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001488 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001489 float f = 1.0f;
1490 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1491 return OVERSCROLL_DAMP_FACTOR * f;
1492 }
1493
Winson Chung321e9ee2010-08-09 13:37:56 -07001494 @Override
1495 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001496 if (DISABLE_TOUCH_INTERACTION) {
1497 return false;
1498 }
1499
Winson Chung45e1d6e2010-11-09 17:19:49 -08001500 // Skip touch handling if there are no pages to swipe
1501 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1502
Michael Jurkab8f06722010-10-10 15:58:46 -07001503 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001504
1505 final int action = ev.getAction();
1506
1507 switch (action & MotionEvent.ACTION_MASK) {
1508 case MotionEvent.ACTION_DOWN:
1509 /*
1510 * If being flinged and user touches, stop the fling. isFinished
1511 * will be false if being flinged.
1512 */
1513 if (!mScroller.isFinished()) {
1514 mScroller.abortAnimation();
1515 }
1516
1517 // Remember where the motion event started
1518 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001519 mDownMotionY = mLastMotionY = ev.getY();
1520 mDownScrollX = getScrollX();
1521 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1522 mParentDownMotionX = p[0];
1523 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001524 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001525 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001526 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001527
1528 // Determine if the down event is within the threshold to be an edge swipe
1529 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1530 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1531 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1532 mDownEventOnEdge = true;
1533 }
1534
Michael Jurka0142d492010-08-25 17:46:15 -07001535 if (mTouchState == TOUCH_STATE_SCROLLING) {
1536 pageBeginMoving();
1537 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001538 break;
1539
1540 case MotionEvent.ACTION_MOVE:
1541 if (mTouchState == TOUCH_STATE_SCROLLING) {
1542 // Scroll to follow the motion event
1543 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001544
1545 if (pointerIndex == -1) return true;
1546
Winson Chung321e9ee2010-08-09 13:37:56 -07001547 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001548 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001549
Adam Cohenaefd4e12011-02-14 16:39:38 -08001550 mTotalMotionX += Math.abs(deltaX);
1551
Winson Chungc0844aa2011-02-02 15:25:58 -08001552 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1553 // keep the remainder because we are actually testing if we've moved from the last
1554 // scrolled position (which is discrete).
1555 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001556 mTouchX += deltaX;
1557 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1558 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001559 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001560 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001561 } else {
1562 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001563 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001564 mLastMotionX = x;
1565 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001566 } else {
1567 awakenScrollBars();
1568 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001569 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1570 // Update the last motion position
1571 mLastMotionX = ev.getX();
1572 mLastMotionY = ev.getY();
1573
1574 // Update the parent down so that our zoom animations take this new movement into
1575 // account
1576 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1577 mParentDownMotionX = pt[0];
1578 mParentDownMotionY = pt[1];
1579 updateDragViewTranslationDuringDrag();
1580
1581 // Find the closest page to the touch point
1582 final int dragViewIndex = indexOfChild(mDragView);
1583 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1584 getViewportWidth());
1585 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1586 + bufferSize);
1587 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1588 - bufferSize);
1589
1590 // Change the drag view if we are hovering over the drop target
1591 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1592 (int) mParentDownMotionX, (int) mParentDownMotionY);
1593 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1594
1595 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1596 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1597 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1598 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1599 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1600 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1601
1602 float parentX = mParentDownMotionX;
1603 int pageIndexToSnapTo = -1;
1604 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1605 pageIndexToSnapTo = dragViewIndex - 1;
1606 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1607 pageIndexToSnapTo = dragViewIndex + 1;
1608 }
1609
1610 final int pageUnderPointIndex = pageIndexToSnapTo;
1611 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1612 mTempVisiblePagesRange[0] = 0;
1613 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07001614 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001615 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1616 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1617 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1618 mSidePageHoverIndex = pageUnderPointIndex;
1619 mSidePageHoverRunnable = new Runnable() {
1620 @Override
1621 public void run() {
1622 // Update the down scroll position to account for the fact that the
1623 // current page is moved
Adam Cohenedb40762013-07-18 16:45:45 -07001624 mDownScrollX = getScrollForPage(pageUnderPointIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001625
1626 // Setup the scroll to the correct page before we swap the views
1627 snapToPage(pageUnderPointIndex);
1628
1629 // For each of the pages between the paged view and the drag view,
1630 // animate them from the previous position to the new position in
1631 // the layout (as a result of the drag view moving in the layout)
1632 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1633 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1634 dragViewIndex + 1 : pageUnderPointIndex;
1635 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1636 dragViewIndex - 1 : pageUnderPointIndex;
1637 for (int i = lowerIndex; i <= upperIndex; ++i) {
1638 View v = getChildAt(i);
1639 // dragViewIndex < pageUnderPointIndex, so after we remove the
1640 // drag view all subsequent views to pageUnderPointIndex will
1641 // shift down.
1642 int oldX = getViewportOffsetX() + getChildOffset(i);
1643 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1644
1645 // Animate the view translation from its old position to its new
1646 // position
1647 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1648 if (anim != null) {
1649 anim.cancel();
1650 }
1651
1652 v.setTranslationX(oldX - newX);
1653 anim = new AnimatorSet();
1654 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1655 anim.playTogether(
1656 ObjectAnimator.ofFloat(v, "translationX", 0f));
1657 anim.start();
1658 v.setTag(anim);
1659 }
1660
1661 removeView(mDragView);
1662 onRemoveView(mDragView, false);
1663 addView(mDragView, pageUnderPointIndex);
1664 onAddView(mDragView, pageUnderPointIndex);
1665 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001666 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001667 }
1668 };
1669 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1670 }
1671 } else {
1672 removeCallbacks(mSidePageHoverRunnable);
1673 mSidePageHoverIndex = -1;
1674 }
Adam Cohen564976a2010-10-13 18:52:07 -07001675 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001676 determineScrollingStart(ev);
1677 }
1678 break;
1679
1680 case MotionEvent.ACTION_UP:
1681 if (mTouchState == TOUCH_STATE_SCROLLING) {
1682 final int activePointerId = mActivePointerId;
1683 final int pointerIndex = ev.findPointerIndex(activePointerId);
1684 final float x = ev.getX(pointerIndex);
1685 final VelocityTracker velocityTracker = mVelocityTracker;
1686 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1687 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001688 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001689 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001690 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1691 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001692
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001693 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1694
Adam Cohen00481b32011-11-18 12:03:48 -08001695 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001696 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001697
Adam Cohenaefd4e12011-02-14 16:39:38 -08001698 // In the case that the page is moved far to one direction and then is flung
1699 // in the opposite direction, we use a threshold to determine whether we should
1700 // just return to the starting page, or if we should skip one further.
1701 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001702 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001703 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001704 returnToOriginalPage = true;
1705 }
1706
Adam Cohenaefd4e12011-02-14 16:39:38 -08001707 int finalPage;
1708 // We give flings precedence over large moves, which is why we short-circuit our
1709 // test for a large move if a fling has been registered. That is, a large
1710 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001711 final boolean isRtl = isLayoutRtl();
1712 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1713 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1714 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1715 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001716 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1717 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001718 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1719 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001720 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001721 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1722 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001723 } else {
1724 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001725 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001726 // at this point we have not moved beyond the touch slop
1727 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1728 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001729 int nextPage = Math.max(0, mCurrentPage - 1);
1730 if (nextPage != mCurrentPage) {
1731 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001732 } else {
1733 snapToDestination();
1734 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001735 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001736 // at this point we have not moved beyond the touch slop
1737 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1738 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001739 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1740 if (nextPage != mCurrentPage) {
1741 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001742 } else {
1743 snapToDestination();
1744 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001745 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1746 // Update the last motion position
1747 mLastMotionX = ev.getX();
1748 mLastMotionY = ev.getY();
1749
1750 // Update the parent down so that our zoom animations take this new movement into
1751 // account
1752 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1753 mParentDownMotionX = pt[0];
1754 mParentDownMotionY = pt[1];
1755 updateDragViewTranslationDuringDrag();
1756 boolean handledFling = false;
1757 if (!DISABLE_FLING_TO_DELETE) {
1758 // Check the velocity and see if we are flinging-to-delete
1759 PointF flingToDeleteVector = isFlingingToDelete();
1760 if (flingToDeleteVector != null) {
1761 onFlingToDelete(flingToDeleteVector);
1762 handledFling = true;
1763 }
1764 }
1765 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1766 (int) mParentDownMotionY)) {
1767 onDropToDelete();
1768 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001769 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001770 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001771 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001772
1773 // Remove the callback to wait for the side page hover timeout
1774 removeCallbacks(mSidePageHoverRunnable);
1775 // End any intermediate reordering states
1776 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001777 break;
1778
1779 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001780 if (mTouchState == TOUCH_STATE_SCROLLING) {
1781 snapToDestination();
1782 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001783 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001784 break;
1785
1786 case MotionEvent.ACTION_POINTER_UP:
1787 onSecondaryPointerUp(ev);
1788 break;
1789 }
1790
1791 return true;
1792 }
1793
Adam Cohen7d30a372013-07-01 17:03:59 -07001794 public void onFlingToDelete(View v) {}
1795 public void onRemoveView(View v, boolean deletePermanently) {}
1796 public void onRemoveViewAnimationCompleted() {}
1797 public void onAddView(View v, int index) {}
1798
1799 private void resetTouchState() {
1800 releaseVelocityTracker();
1801 endReordering();
1802 mTouchState = TOUCH_STATE_REST;
1803 mActivePointerId = INVALID_POINTER;
1804 mDownEventOnEdge = false;
1805 }
1806
1807 protected void onUnhandledTap(MotionEvent ev) {}
1808
Winson Chung185d7162011-02-28 13:47:29 -08001809 @Override
1810 public boolean onGenericMotionEvent(MotionEvent event) {
1811 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1812 switch (event.getAction()) {
1813 case MotionEvent.ACTION_SCROLL: {
1814 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1815 final float vscroll;
1816 final float hscroll;
1817 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1818 vscroll = 0;
1819 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1820 } else {
1821 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1822 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1823 }
1824 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001825 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1826 : (hscroll > 0 || vscroll > 0);
1827 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001828 scrollRight();
1829 } else {
1830 scrollLeft();
1831 }
1832 return true;
1833 }
1834 }
1835 }
1836 }
1837 return super.onGenericMotionEvent(event);
1838 }
1839
Michael Jurkab8f06722010-10-10 15:58:46 -07001840 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1841 if (mVelocityTracker == null) {
1842 mVelocityTracker = VelocityTracker.obtain();
1843 }
1844 mVelocityTracker.addMovement(ev);
1845 }
1846
1847 private void releaseVelocityTracker() {
1848 if (mVelocityTracker != null) {
1849 mVelocityTracker.recycle();
1850 mVelocityTracker = null;
1851 }
1852 }
1853
Winson Chung321e9ee2010-08-09 13:37:56 -07001854 private void onSecondaryPointerUp(MotionEvent ev) {
1855 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1856 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1857 final int pointerId = ev.getPointerId(pointerIndex);
1858 if (pointerId == mActivePointerId) {
1859 // This was our active pointer going up. Choose a new
1860 // active pointer and adjust accordingly.
1861 // TODO: Make this decision more intelligent.
1862 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1863 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1864 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001865 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001866 mActivePointerId = ev.getPointerId(newPointerIndex);
1867 if (mVelocityTracker != null) {
1868 mVelocityTracker.clear();
1869 }
1870 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001871 }
1872
Winson Chung321e9ee2010-08-09 13:37:56 -07001873 @Override
1874 public void requestChildFocus(View child, View focused) {
1875 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001876 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001877 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001878 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001879 }
1880 }
1881
Winson Chung1908d072011-02-24 18:09:44 -08001882 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001883 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001884 }
1885
Adam Cohen7d30a372013-07-01 17:03:59 -07001886 int getPageNearestToPoint(float x) {
1887 int index = 0;
1888 for (int i = 0; i < getChildCount(); ++i) {
1889 if (x < getChildAt(i).getRight() - getScrollX()) {
1890 return index;
1891 } else {
1892 index++;
1893 }
1894 }
1895 return Math.min(index, getChildCount() - 1);
1896 }
1897
Adam Cohend19d3ca2010-09-15 14:43:42 -07001898 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001899 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001900 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001901 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001902 final int childCount = getChildCount();
1903 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001904 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001905 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001906 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001907 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001908 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1909 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1910 minDistanceFromScreenCenter = distanceFromScreenCenter;
1911 minDistanceFromScreenCenterIndex = i;
1912 }
1913 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001914 return minDistanceFromScreenCenterIndex;
1915 }
1916
1917 protected void snapToDestination() {
1918 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001919 }
1920
Adam Cohene0f66b52010-11-23 15:06:07 -08001921 private static class ScrollInterpolator implements Interpolator {
1922 public ScrollInterpolator() {
1923 }
1924
1925 public float getInterpolation(float t) {
1926 t -= 1.0f;
1927 return t*t*t*t*t + 1;
1928 }
1929 }
1930
1931 // We want the duration of the page snap animation to be influenced by the distance that
1932 // the screen has to travel, however, we don't want this duration to be effected in a
1933 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1934 // of travel has on the overall snap duration.
1935 float distanceInfluenceForSnapDuration(float f) {
1936 f -= 0.5f; // center the values about 0.
1937 f *= 0.3f * Math.PI / 2.0f;
1938 return (float) Math.sin(f);
1939 }
1940
Michael Jurka0142d492010-08-25 17:46:15 -07001941 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001942 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001943 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001944
Adam Cohenedb40762013-07-18 16:45:45 -07001945 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08001946 int delta = newX - mUnboundedScrollX;
1947 int duration = 0;
1948
Adam Cohen265b9a62011-12-07 14:37:18 -08001949 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001950 // If the velocity is low enough, then treat this more as an automatic page advance
1951 // as opposed to an apparent physical response to flinging
1952 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1953 return;
1954 }
1955
1956 // Here we compute a "distance" that will be used in the computation of the overall
1957 // snap duration. This is a function of the actual distance that needs to be traveled;
1958 // we keep this value close to half screen size in order to reduce the variance in snap
1959 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001960 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001961 float distance = halfScreenSize + halfScreenSize *
1962 distanceInfluenceForSnapDuration(distanceRatio);
1963
1964 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001965 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001966
1967 // we want the page's snap velocity to approximately match the velocity at which the
1968 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001969 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1970 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001971
1972 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001973 }
1974
1975 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001976 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001977 }
1978
Adam Cohen7d30a372013-07-01 17:03:59 -07001979 protected void snapToPageImmediately(int whichPage) {
1980 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1981 }
1982
Michael Jurka0142d492010-08-25 17:46:15 -07001983 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001984 snapToPage(whichPage, duration, false);
1985 }
1986
1987 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07001988 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07001989
Adam Cohenedb40762013-07-18 16:45:45 -07001990 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08001991 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001992 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07001993 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07001994 }
1995
1996 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001997 snapToPage(whichPage, delta, duration, false);
1998 }
Michael Jurka0142d492010-08-25 17:46:15 -07001999
Adam Cohen7d30a372013-07-01 17:03:59 -07002000 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2001 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002002 View focusedChild = getFocusedChild();
2003 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002004 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002005 focusedChild.clearFocus();
2006 }
2007
2008 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002009 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002010 if (immediate) {
2011 duration = 0;
2012 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002013 duration = Math.abs(delta);
2014 }
2015
2016 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002017 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002018
Michael Jurka0142d492010-08-25 17:46:15 -07002019 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002020
2021 // Trigger a compute() to finish switching pages if necessary
2022 if (immediate) {
2023 computeScroll();
2024 }
2025
Winson Chung9c0565f2013-07-19 13:49:06 -07002026 // Defer loading associated pages until the scroll settles
2027 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2028
Adam Cohen7d30a372013-07-01 17:03:59 -07002029 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002030 invalidate();
2031 }
2032
Winson Chung321e9ee2010-08-09 13:37:56 -07002033 public void scrollLeft() {
2034 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002035 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002036 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002037 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002038 }
2039 }
2040
2041 public void scrollRight() {
2042 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002043 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002044 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002045 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002046 }
2047 }
2048
Winson Chung86f77532010-08-24 11:08:22 -07002049 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002050 int result = -1;
2051 if (v != null) {
2052 ViewParent vp = v.getParent();
2053 int count = getChildCount();
2054 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002055 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002056 return i;
2057 }
2058 }
2059 }
2060 return result;
2061 }
2062
2063 /**
2064 * @return True is long presses are still allowed for the current touch
2065 */
2066 public boolean allowLongPress() {
2067 return mAllowLongPress;
2068 }
2069
Michael Jurka0142d492010-08-25 17:46:15 -07002070 /**
2071 * Set true to allow long-press events to be triggered, usually checked by
2072 * {@link Launcher} to accept or block dpad-initiated long-presses.
2073 */
2074 public void setAllowLongPress(boolean allowLongPress) {
2075 mAllowLongPress = allowLongPress;
2076 }
2077
Winson Chung321e9ee2010-08-09 13:37:56 -07002078 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002079 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002080
2081 SavedState(Parcelable superState) {
2082 super(superState);
2083 }
2084
2085 private SavedState(Parcel in) {
2086 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002087 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002088 }
2089
2090 @Override
2091 public void writeToParcel(Parcel out, int flags) {
2092 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002093 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002094 }
2095
2096 public static final Parcelable.Creator<SavedState> CREATOR =
2097 new Parcelable.Creator<SavedState>() {
2098 public SavedState createFromParcel(Parcel in) {
2099 return new SavedState(in);
2100 }
2101
2102 public SavedState[] newArray(int size) {
2103 return new SavedState[size];
2104 }
2105 };
2106 }
2107
Winson Chungf314b0e2011-08-16 11:54:27 -07002108 protected void loadAssociatedPages(int page) {
2109 loadAssociatedPages(page, false);
2110 }
2111 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002112 if (mContentIsRefreshable) {
2113 final int count = getChildCount();
2114 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002115 int lowerPageBound = getAssociatedLowerPageBound(page);
2116 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002117 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2118 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002119 // First, clear any pages that should no longer be loaded
2120 for (int i = 0; i < count; ++i) {
2121 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002122 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002123 if (layout.getPageChildCount() > 0) {
2124 layout.removeAllViewsOnPage();
2125 }
2126 mDirtyPageContent.set(i, true);
2127 }
2128 }
2129 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002130 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002131 if ((i != page) && immediateAndOnly) {
2132 continue;
2133 }
Michael Jurka0142d492010-08-25 17:46:15 -07002134 if (lowerPageBound <= i && i <= upperPageBound) {
2135 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002136 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002137 mDirtyPageContent.set(i, false);
2138 }
Winson Chung86f77532010-08-24 11:08:22 -07002139 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002140 }
2141 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002142 }
2143 }
2144
Winson Chunge3193b92010-09-10 11:44:42 -07002145 protected int getAssociatedLowerPageBound(int page) {
2146 return Math.max(0, page - 1);
2147 }
2148 protected int getAssociatedUpperPageBound(int page) {
2149 final int count = getChildCount();
2150 return Math.min(page + 1, count - 1);
2151 }
2152
Winson Chung86f77532010-08-24 11:08:22 -07002153 /**
2154 * This method is called ONLY to synchronize the number of pages that the paged view has.
2155 * To actually fill the pages with information, implement syncPageItems() below. It is
2156 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2157 * and therefore, individual page items do not need to be updated in this method.
2158 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002159 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002160
2161 /**
2162 * This method is called to synchronize the items that are on a particular page. If views on
2163 * the page can be reused, then they should be updated within this method.
2164 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002165 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002166
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002167 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002168 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002169 }
2170 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002171 invalidatePageData(currentPage, false);
2172 }
2173 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002174 if (!mIsDataReady) {
2175 return;
2176 }
2177
Michael Jurka0142d492010-08-25 17:46:15 -07002178 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002179 // Force all scrolling-related behavior to end
2180 mScroller.forceFinished(true);
2181 mNextPage = INVALID_PAGE;
2182
Michael Jurka0142d492010-08-25 17:46:15 -07002183 // Update all the pages
2184 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002185
Winson Chung5a808352011-06-27 19:08:49 -07002186 // We must force a measure after we've loaded the pages to update the content width and
2187 // to determine the full scroll width
2188 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2189 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2190
2191 // Set a new page as the current page if necessary
2192 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002193 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002194 }
2195
Michael Jurka0142d492010-08-25 17:46:15 -07002196 // Mark each of the pages as dirty
2197 final int count = getChildCount();
2198 mDirtyPageContent.clear();
2199 for (int i = 0; i < count; ++i) {
2200 mDirtyPageContent.add(true);
2201 }
2202
2203 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002204 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002205 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002206 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002207 }
Winson Chung007c6982011-06-14 13:27:53 -07002208
Adam Cohen7d30a372013-07-01 17:03:59 -07002209 // Animate the drag view back to the original position
2210 void animateDragViewToOriginalPosition() {
2211 if (mDragView != null) {
2212 AnimatorSet anim = new AnimatorSet();
2213 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2214 anim.playTogether(
2215 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2216 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2217 anim.addListener(new AnimatorListenerAdapter() {
2218 @Override
2219 public void onAnimationEnd(Animator animation) {
2220 onPostReorderingAnimationCompleted();
2221 }
2222 });
2223 anim.start();
2224 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002225 }
2226
Adam Cohen7d30a372013-07-01 17:03:59 -07002227 // "Zooms out" the PagedView to reveal more side pages
2228 protected boolean zoomOut() {
2229 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2230 mZoomInOutAnim.cancel();
2231 }
2232
2233 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2234 mZoomInOutAnim = new AnimatorSet();
2235 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2236 mZoomInOutAnim.playTogether(
2237 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2238 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2239 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2240 @Override
2241 public void onAnimationStart(Animator animation) {
2242 // Show the delete drop target
2243 if (mDeleteDropTarget != null) {
2244 mDeleteDropTarget.setVisibility(View.VISIBLE);
2245 mDeleteDropTarget.animate().alpha(1f)
2246 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2247 .setListener(new AnimatorListenerAdapter() {
2248 @Override
2249 public void onAnimationStart(Animator animation) {
2250 mDeleteDropTarget.setAlpha(0f);
2251 }
2252 });
2253 }
2254 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002255 @Override
2256 public void onAnimationEnd(Animator animation) {
2257 // Update the visible pages
2258 invalidate();
2259 }
Adam Cohen7d30a372013-07-01 17:03:59 -07002260 });
2261 mZoomInOutAnim.start();
2262 return true;
2263 }
2264 return false;
2265 }
2266
2267 protected void onStartReordering() {
2268 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2269 mTouchState = TOUCH_STATE_REORDERING;
2270 mIsReordering = true;
2271
2272 // Mark all the non-widget pages as invisible
Winson Chungc9ca2982013-07-19 12:07:38 -07002273 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002274 for (int i = 0; i < getPageCount(); ++i) {
2275 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2276 getPageAt(i).setAlpha(0f);
2277 }
2278 }
2279
2280 // We must invalidate to trigger a redraw to update the layers such that the drag view
2281 // is always drawn on top
2282 invalidate();
2283 }
2284
2285 private void onPostReorderingAnimationCompleted() {
2286 // Trigger the callback when reordering has settled
2287 --mPostReorderingPreZoomInRemainingAnimationCount;
2288 if (mPostReorderingPreZoomInRunnable != null &&
2289 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2290 mPostReorderingPreZoomInRunnable.run();
2291 mPostReorderingPreZoomInRunnable = null;
2292 }
2293 }
2294
2295 protected void onEndReordering() {
2296 mIsReordering = false;
2297
2298 // Mark all the non-widget pages as visible again
Winson Chungc9ca2982013-07-19 12:07:38 -07002299 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002300 for (int i = 0; i < getPageCount(); ++i) {
2301 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2302 getPageAt(i).setAlpha(1f);
2303 }
2304 }
2305 }
2306
2307 public boolean startReordering() {
2308 int dragViewIndex = getPageNearestToCenterOfScreen();
2309 mTempVisiblePagesRange[0] = 0;
2310 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07002311 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002312 mReorderingStarted = true;
2313
2314 // Check if we are within the reordering range
2315 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2316 dragViewIndex <= mTempVisiblePagesRange[1]) {
2317 if (zoomOut()) {
2318 // Find the drag view under the pointer
2319 mDragView = getChildAt(dragViewIndex);
2320
2321 onStartReordering();
2322 }
2323 return true;
2324 }
2325 return false;
2326 }
2327
2328 boolean isReordering(boolean testTouchState) {
2329 boolean state = mIsReordering;
2330 if (testTouchState) {
2331 state &= (mTouchState == TOUCH_STATE_REORDERING);
2332 }
2333 return state;
2334 }
2335 void endReordering() {
2336 // For simplicity, we call endReordering sometimes even if reordering was never started.
2337 // In that case, we don't want to do anything.
2338 if (!mReorderingStarted) return;
2339 mReorderingStarted = false;
2340
2341 // If we haven't flung-to-delete the current child, then we just animate the drag view
2342 // back into position
2343 final Runnable onCompleteRunnable = new Runnable() {
2344 @Override
2345 public void run() {
2346 onEndReordering();
2347 }
2348 };
2349 if (!mDeferringForDelete) {
2350 mPostReorderingPreZoomInRunnable = new Runnable() {
2351 public void run() {
2352 zoomIn(onCompleteRunnable);
2353 };
2354 };
2355
2356 mPostReorderingPreZoomInRemainingAnimationCount =
2357 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2358 // Snap to the current page
2359 snapToPage(indexOfChild(mDragView), 0);
2360 // Animate the drag view back to the front position
2361 animateDragViewToOriginalPosition();
2362 } else {
2363 // Handled in post-delete-animation-callbacks
2364 }
2365 }
2366
2367 // "Zooms in" the PagedView to highlight the current page
2368 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2369 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2370 mZoomInOutAnim.cancel();
2371 }
2372 if (getScaleX() < 1f || getScaleY() < 1f) {
2373 mZoomInOutAnim = new AnimatorSet();
2374 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2375 mZoomInOutAnim.playTogether(
2376 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2377 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2378 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2379 @Override
2380 public void onAnimationStart(Animator animation) {
2381 // Hide the delete drop target
2382 if (mDeleteDropTarget != null) {
2383 mDeleteDropTarget.animate().alpha(0f)
2384 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2385 .setListener(new AnimatorListenerAdapter() {
2386 @Override
2387 public void onAnimationEnd(Animator animation) {
2388 mDeleteDropTarget.setVisibility(View.GONE);
2389 }
2390 });
2391 }
2392 }
2393 @Override
2394 public void onAnimationCancel(Animator animation) {
2395 mDragView = null;
2396 }
2397 @Override
2398 public void onAnimationEnd(Animator animation) {
2399 mDragView = null;
2400 if (onCompleteRunnable != null) {
2401 onCompleteRunnable.run();
2402 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002403 // Update the visible pages
2404 invalidate();
Adam Cohen7d30a372013-07-01 17:03:59 -07002405 }
2406 });
2407 mZoomInOutAnim.start();
2408 return true;
2409 } else {
2410 if (onCompleteRunnable != null) {
2411 onCompleteRunnable.run();
2412 }
2413 }
2414 return false;
2415 }
2416
2417 /*
2418 * Flinging to delete - IN PROGRESS
2419 */
2420 private PointF isFlingingToDelete() {
2421 ViewConfiguration config = ViewConfiguration.get(getContext());
2422 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2423
2424 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2425 // Do a quick dot product test to ensure that we are flinging upwards
2426 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2427 mVelocityTracker.getYVelocity());
2428 PointF upVec = new PointF(0f, -1f);
2429 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2430 (vel.length() * upVec.length()));
2431 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2432 return vel;
2433 }
2434 }
2435 return null;
2436 }
2437
2438 /**
2439 * Creates an animation from the current drag view along its current velocity vector.
2440 * For this animation, the alpha runs for a fixed duration and we update the position
2441 * progressively.
2442 */
2443 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2444 private View mDragView;
2445 private PointF mVelocity;
2446 private Rect mFrom;
2447 private long mPrevTime;
2448 private float mFriction;
2449
2450 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2451
2452 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2453 long startTime, float friction) {
2454 mDragView = dragView;
2455 mVelocity = vel;
2456 mFrom = from;
2457 mPrevTime = startTime;
2458 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2459 }
2460
2461 @Override
2462 public void onAnimationUpdate(ValueAnimator animation) {
2463 float t = ((Float) animation.getAnimatedValue()).floatValue();
2464 long curTime = AnimationUtils.currentAnimationTimeMillis();
2465
2466 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2467 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2468
2469 mDragView.setTranslationX(mFrom.left);
2470 mDragView.setTranslationY(mFrom.top);
2471 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2472
2473 mVelocity.x *= mFriction;
2474 mVelocity.y *= mFriction;
2475 mPrevTime = curTime;
2476 }
2477 };
2478
2479 private static final int ANIM_TAG_KEY = 100;
2480
2481 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2482 return new Runnable() {
2483 @Override
2484 public void run() {
2485 int dragViewIndex = indexOfChild(dragView);
2486
2487 // For each of the pages around the drag view, animate them from the previous
2488 // position to the new position in the layout (as a result of the drag view moving
2489 // in the layout)
2490 // NOTE: We can make an assumption here because we have side-bound pages that we
2491 // will always have pages to animate in from the left
Winson Chungc9ca2982013-07-19 12:07:38 -07002492 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002493 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2494 boolean slideFromLeft = (isLastWidgetPage ||
2495 dragViewIndex > mTempVisiblePagesRange[0]);
2496
2497 // Setup the scroll to the correct page before we swap the views
2498 if (slideFromLeft) {
2499 snapToPageImmediately(dragViewIndex - 1);
2500 }
2501
2502 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2503 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2504 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2505 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2506 ArrayList<Animator> animations = new ArrayList<Animator>();
2507 for (int i = lowerIndex; i <= upperIndex; ++i) {
2508 View v = getChildAt(i);
2509 // dragViewIndex < pageUnderPointIndex, so after we remove the
2510 // drag view all subsequent views to pageUnderPointIndex will
2511 // shift down.
2512 int oldX = 0;
2513 int newX = 0;
2514 if (slideFromLeft) {
2515 if (i == 0) {
2516 // Simulate the page being offscreen with the page spacing
2517 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2518 - mPageSpacing;
2519 } else {
2520 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2521 }
2522 newX = getViewportOffsetX() + getChildOffset(i);
2523 } else {
2524 oldX = getChildOffset(i) - getChildOffset(i - 1);
2525 newX = 0;
2526 }
2527
2528 // Animate the view translation from its old position to its new
2529 // position
2530 AnimatorSet anim = (AnimatorSet) v.getTag();
2531 if (anim != null) {
2532 anim.cancel();
2533 }
2534
2535 // Note: Hacky, but we want to skip any optimizations to not draw completely
2536 // hidden views
2537 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2538 v.setTranslationX(oldX - newX);
2539 anim = new AnimatorSet();
2540 anim.playTogether(
2541 ObjectAnimator.ofFloat(v, "translationX", 0f),
2542 ObjectAnimator.ofFloat(v, "alpha", 1f));
2543 animations.add(anim);
2544 v.setTag(ANIM_TAG_KEY, anim);
2545 }
2546
2547 AnimatorSet slideAnimations = new AnimatorSet();
2548 slideAnimations.playTogether(animations);
2549 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2550 slideAnimations.addListener(new AnimatorListenerAdapter() {
2551 @Override
2552 public void onAnimationEnd(Animator animation) {
2553 final Runnable onCompleteRunnable = new Runnable() {
2554 @Override
2555 public void run() {
2556 mDeferringForDelete = false;
2557 onEndReordering();
2558 onRemoveViewAnimationCompleted();
2559 }
2560 };
2561 zoomIn(onCompleteRunnable);
2562 }
2563 });
2564 slideAnimations.start();
2565
2566 removeView(dragView);
2567 onRemoveView(dragView, true);
2568 }
2569 };
2570 }
2571
2572 public void onFlingToDelete(PointF vel) {
2573 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2574
2575 // NOTE: Because it takes time for the first frame of animation to actually be
2576 // called and we expect the animation to be a continuation of the fling, we have
2577 // to account for the time that has elapsed since the fling finished. And since
2578 // we don't have a startDelay, we will always get call to update when we call
2579 // start() (which we want to ignore).
2580 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2581 private int mCount = -1;
2582 private long mStartTime;
2583 private float mOffset;
2584 /* Anonymous inner class ctor */ {
2585 mStartTime = startTime;
2586 }
2587
2588 @Override
2589 public float getInterpolation(float t) {
2590 if (mCount < 0) {
2591 mCount++;
2592 } else if (mCount == 0) {
2593 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2594 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2595 mCount++;
2596 }
2597 return Math.min(1f, mOffset + t);
2598 }
2599 };
2600
2601 final Rect from = new Rect();
2602 final View dragView = mDragView;
2603 from.left = (int) dragView.getTranslationX();
2604 from.top = (int) dragView.getTranslationY();
2605 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2606 from, startTime, FLING_TO_DELETE_FRICTION);
2607
2608 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2609
2610 // Create and start the animation
2611 ValueAnimator mDropAnim = new ValueAnimator();
2612 mDropAnim.setInterpolator(tInterpolator);
2613 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2614 mDropAnim.setFloatValues(0f, 1f);
2615 mDropAnim.addUpdateListener(updateCb);
2616 mDropAnim.addListener(new AnimatorListenerAdapter() {
2617 public void onAnimationEnd(Animator animation) {
2618 onAnimationEndRunnable.run();
2619 }
2620 });
2621 mDropAnim.start();
2622 mDeferringForDelete = true;
2623 }
2624
2625 /* Drag to delete */
2626 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2627 if (mDeleteDropTarget != null) {
2628 mAltTmpRect.set(0, 0, 0, 0);
2629 View parent = (View) mDeleteDropTarget.getParent();
2630 if (parent != null) {
2631 parent.getGlobalVisibleRect(mAltTmpRect);
2632 }
2633 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2634 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2635 return mTmpRect.contains(x, y);
2636 }
2637 return false;
2638 }
2639
2640 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2641
2642 private void onDropToDelete() {
2643 final View dragView = mDragView;
2644
2645 final float toScale = 0f;
2646 final float toAlpha = 0f;
2647
2648 // Create and start the complex animation
2649 ArrayList<Animator> animations = new ArrayList<Animator>();
2650 AnimatorSet motionAnim = new AnimatorSet();
2651 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2652 motionAnim.playTogether(
2653 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2654 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2655 animations.add(motionAnim);
2656
2657 AnimatorSet alphaAnim = new AnimatorSet();
2658 alphaAnim.setInterpolator(new LinearInterpolator());
2659 alphaAnim.playTogether(
2660 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2661 animations.add(alphaAnim);
2662
2663 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2664
2665 AnimatorSet anim = new AnimatorSet();
2666 anim.playTogether(animations);
2667 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2668 anim.addListener(new AnimatorListenerAdapter() {
2669 public void onAnimationEnd(Animator animation) {
2670 onAnimationEndRunnable.run();
2671 }
2672 });
2673 anim.start();
2674
2675 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002676 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002677
2678 /* Accessibility */
2679 @Override
2680 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2681 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002682 info.setScrollable(getPageCount() > 1);
2683 if (getCurrentPage() < getPageCount() - 1) {
2684 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2685 }
2686 if (getCurrentPage() > 0) {
2687 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2688 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002689 }
2690
2691 @Override
2692 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2693 super.onInitializeAccessibilityEvent(event);
2694 event.setScrollable(true);
2695 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2696 event.setFromIndex(mCurrentPage);
2697 event.setToIndex(mCurrentPage);
2698 event.setItemCount(getChildCount());
2699 }
2700 }
2701
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002702 @Override
2703 public boolean performAccessibilityAction(int action, Bundle arguments) {
2704 if (super.performAccessibilityAction(action, arguments)) {
2705 return true;
2706 }
2707 switch (action) {
2708 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2709 if (getCurrentPage() < getPageCount() - 1) {
2710 scrollRight();
2711 return true;
2712 }
2713 } break;
2714 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2715 if (getCurrentPage() > 0) {
2716 scrollLeft();
2717 return true;
2718 }
2719 } break;
2720 }
2721 return false;
2722 }
2723
Adam Cohen0ffac432013-07-10 11:19:26 -07002724 protected String getCurrentPageDescription() {
2725 return String.format(getContext().getString(R.string.default_scroll_format),
2726 getNextPage() + 1, getChildCount());
2727 }
2728
Winson Chungd11265e2011-08-30 13:37:23 -07002729 @Override
2730 public boolean onHoverEvent(android.view.MotionEvent event) {
2731 return true;
2732 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002733}