blob: 81a842e3522909815de4e7e27235b3e4cfee92af [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;
Winson Chung6a0f57d2011-06-29 20:10:49 -070047import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070048import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070049import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070050import android.view.animation.AnimationUtils;
51import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080052import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070053import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070054import android.widget.Scroller;
55
Winson Chung6a0f57d2011-06-29 20:10:49 -070056import java.util.ArrayList;
57
Winson Chung321e9ee2010-08-09 13:37:56 -070058/**
59 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070060 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070061 */
Michael Jurka8b805b12012-04-18 14:23:14 -070062public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070063 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070064 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070065 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070066
Winson Chung86f77532010-08-24 11:08:22 -070067 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070068 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070069
Adam Cohen7d30a372013-07-01 17:03:59 -070070 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070071 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070072 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070073
Adam Cohenb5ba0972011-09-07 18:02:31 -070074 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070075 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080076
Adam Cohenb64cb5a2011-02-15 13:53:42 -080077 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080078 // The page is moved more than halfway, automatically move to the next page on touch up.
79 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080080
Adam Cohen265b9a62011-12-07 14:37:18 -080081 // The following constants need to be scaled based on density. The scaled versions will be
82 // assigned to the corresponding member variables below.
83 private static final int FLING_THRESHOLD_VELOCITY = 500;
84 private static final int MIN_SNAP_VELOCITY = 1500;
85 private static final int MIN_FLING_VELOCITY = 250;
86
Adam Cohen7d30a372013-07-01 17:03:59 -070087 // We are disabling touch interaction of the widget region for factory ROM.
88 private static final boolean DISABLE_TOUCH_INTERACTION = false;
89 private static final boolean DISABLE_TOUCH_SIDE_PAGES = false;
Adam Cohendedbd962013-07-11 14:21:49 -070090 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070091
Winson Chung8aad6102012-05-11 16:27:49 -070092 static final int AUTOMATIC_PAGE_SPACING = -1;
93
Adam Cohen265b9a62011-12-07 14:37:18 -080094 protected int mFlingThresholdVelocity;
95 protected int mMinFlingVelocity;
96 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -070097
Adam Cohenb5ba0972011-09-07 18:02:31 -070098 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -070099 protected float mSmoothingTime;
100 protected float mTouchX;
101
102 protected boolean mFirstLayout = true;
103
104 protected int mCurrentPage;
Adam Cohene61a9a22013-06-11 15:45:31 -0700105 protected int mChildCountOnLastMeasure;
106
Michael Jurka0142d492010-08-25 17:46:15 -0700107 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800108 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700109 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700110 private VelocityTracker mVelocityTracker;
111
Adam Cohen7d30a372013-07-01 17:03:59 -0700112 private float mParentDownMotionX;
113 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700114 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700115 private float mDownMotionY;
116 private float mDownScrollX;
Michael Jurka7426c422010-11-11 15:23:47 -0800117 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800118 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800119 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800120 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700121 private int mLastScreenCenter = -1;
Adam Cohen73894962011-10-31 13:17:17 -0700122 private int[] mChildOffsets;
123 private int[] mChildRelativeOffsets;
124 private int[] mChildOffsetsWithLayoutScale;
Winson Chung321e9ee2010-08-09 13:37:56 -0700125
Michael Jurka0142d492010-08-25 17:46:15 -0700126 protected final static int TOUCH_STATE_REST = 0;
127 protected final static int TOUCH_STATE_SCROLLING = 1;
128 protected final static int TOUCH_STATE_PREV_PAGE = 2;
129 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700130 protected final static int TOUCH_STATE_REORDERING = 4;
131
Adam Cohene45440e2010-10-14 18:33:38 -0700132 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700133
Michael Jurka0142d492010-08-25 17:46:15 -0700134 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700135 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700136
Michael Jurka0142d492010-08-25 17:46:15 -0700137 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700138
Michael Jurka7426c422010-11-11 15:23:47 -0800139 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700140 private int mPagingTouchSlop;
141 private int mMaximumVelocity;
Winson Chung1908d072011-02-24 18:09:44 -0800142 private int mMinimumWidth;
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 Jurka8c920dd2011-01-20 14:16:56 -0800163 // parameter that adjusts the layout to be optimized for pages with that scale factor
Michael Jurkad3ef3062010-11-23 16:23:58 -0800164 protected float mLayoutScale = 1.0f;
165
Michael Jurka5f1c5092010-09-03 14:15:02 -0700166 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700167
Michael Jurka5f1c5092010-09-03 14:15:02 -0700168 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700169
Winson Chung86f77532010-08-24 11:08:22 -0700170 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700171
Michael Jurkae326f182011-11-21 14:05:46 -0800172 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700173
Michael Jurka0142d492010-08-25 17:46:15 -0700174 // If true, syncPages and syncPageItems will be called to refresh pages
175 protected boolean mContentIsRefreshable = true;
176
177 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700178 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700179
180 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
181 // to switch to a new page
182 protected boolean mUsePagingTouchSlop = true;
183
Michael Jurka8b805b12012-04-18 14:23:14 -0700184 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700185 // (SmoothPagedView does this)
186 protected boolean mDeferScrollUpdate = false;
187
Patrick Dubroy1262e362010-10-06 15:49:50 -0700188 protected boolean mIsPageMoving = false;
189
Winson Chungf0ea4d32011-06-06 14:27:16 -0700190 // All syncs and layout passes are deferred until data is ready.
191 protected boolean mIsDataReady = false;
192
Adam Cohen7d30a372013-07-01 17:03:59 -0700193 protected boolean mAllowLongPress = true;
194
Winson Chungd2be3812013-07-16 11:11:32 -0700195 // Page Indicator
196 private int mPageIndicatorViewId;
197 private PageIndicator mPageIndicator;
Winson Chung007c6982011-06-14 13:27:53 -0700198
Adam Cohen7d30a372013-07-01 17:03:59 -0700199 // The viewport whether the pages are to be contained (the actual view may be larger than the
200 // viewport)
201 private Rect mViewport = new Rect();
202
203 // Reordering
204 // We use the min scale to determine how much to expand the actually PagedView measured
205 // dimensions such that when we are zoomed out, the view is not clipped
206 private int REORDERING_DROP_REPOSITION_DURATION = 200;
207 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
208 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
209 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 300;
210 private float REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE = 0.1f;
211 private long REORDERING_DELETE_DROP_TARGET_FADE_DURATION = 150;
212 private float mMinScale = 1f;
213 protected View mDragView;
214 protected AnimatorSet mZoomInOutAnim;
215 private Runnable mSidePageHoverRunnable;
216 private int mSidePageHoverIndex = -1;
217 // This variable's scope is only for the duration of startReordering() and endReordering()
218 private boolean mReorderingStarted = false;
219 // This variable's scope is for the duration of startReordering() and after the zoomIn()
220 // animation after endReordering()
221 private boolean mIsReordering;
222 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
223 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
224 private int mPostReorderingPreZoomInRemainingAnimationCount;
225 private Runnable mPostReorderingPreZoomInRunnable;
226
227 // Edge swiping
228 private boolean mOnlyAllowEdgeSwipes = false;
229 private boolean mDownEventOnEdge = false;
230 private int mEdgeSwipeRegionSize = 0;
231
232 // Convenience/caching
233 private Matrix mTmpInvMatrix = new Matrix();
234 private float[] mTmpPoint = new float[2];
235 private Rect mTmpRect = new Rect();
236 private Rect mAltTmpRect = new Rect();
237
238 // Fling to delete
239 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
240 private float FLING_TO_DELETE_FRICTION = 0.035f;
241 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
242 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
243 protected int mFlingToDeleteThresholdVelocity = -1400;
244 // Drag to delete
245 private boolean mDeferringForDelete = false;
246 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
247 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
248
249 // Drop to delete
250 private View mDeleteDropTarget;
251
252 private boolean mAutoComputePageSpacing = false;
253 private boolean mRecomputePageSpacing = false;
254
255 // Bouncer
256 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700257
Winson Chung86f77532010-08-24 11:08:22 -0700258 public interface PageSwitchListener {
259 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700260 }
261
Winson Chung321e9ee2010-08-09 13:37:56 -0700262 public PagedView(Context context) {
263 this(context, null);
264 }
265
266 public PagedView(Context context, AttributeSet attrs) {
267 this(context, attrs, 0);
268 }
269
270 public PagedView(Context context, AttributeSet attrs, int defStyle) {
271 super(context, attrs, defStyle);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700272 TypedArray a = context.obtainStyledAttributes(attrs,
273 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800274 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700275 if (mPageSpacing < 0) {
276 mAutoComputePageSpacing = mRecomputePageSpacing = true;
277 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700278 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800279 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700280 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800281 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700282 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800283 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700284 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800285 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700286 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700287 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700288 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700289 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700290 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700291 a.recycle();
292
Winson Chung321e9ee2010-08-09 13:37:56 -0700293 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700294 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700295 }
296
297 /**
298 * Initializes various states for this workspace.
299 */
Michael Jurka0142d492010-08-25 17:46:15 -0700300 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700301 mDirtyPageContent = new ArrayList<Boolean>();
302 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800303 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700304 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700305 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700306
307 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700308 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700309 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
310 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700311 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800312
Adam Cohen7d30a372013-07-01 17:03:59 -0700313 // Scale the fling-to-delete threshold by the density
314 mFlingToDeleteThresholdVelocity =
315 (int) (mFlingToDeleteThresholdVelocity * mDensity);
316
Adam Cohen265b9a62011-12-07 14:37:18 -0800317 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
318 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
319 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700320 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700321 }
322
Winson Chungd2be3812013-07-16 11:11:32 -0700323 protected void onAttachedToWindow() {
324 // Hook up the page indicator
325 ViewGroup parent = (ViewGroup) getParent();
326 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
327 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
328 mPageIndicator.removeAllMarkers();
329 mPageIndicator.addMarkers(getChildCount());
330 }
331 }
332
333 protected void onDetachedFromWindow() {
334 // Unhook the page indicator
335 mPageIndicator = null;
336 }
337
Adam Cohen7d30a372013-07-01 17:03:59 -0700338 void setDeleteDropTarget(View v) {
339 mDeleteDropTarget = v;
340 }
341
342 // Convenience methods to map points from self to parent and vice versa
343 float[] mapPointFromViewToParent(View v, float x, float y) {
344 mTmpPoint[0] = x;
345 mTmpPoint[1] = y;
346 v.getMatrix().mapPoints(mTmpPoint);
347 mTmpPoint[0] += v.getLeft();
348 mTmpPoint[1] += v.getTop();
349 return mTmpPoint;
350 }
351 float[] mapPointFromParentToView(View v, float x, float y) {
352 mTmpPoint[0] = x - v.getLeft();
353 mTmpPoint[1] = y - v.getTop();
354 v.getMatrix().invert(mTmpInvMatrix);
355 mTmpInvMatrix.mapPoints(mTmpPoint);
356 return mTmpPoint;
357 }
358
359 void updateDragViewTranslationDuringDrag() {
360 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
361 float y = mLastMotionY - mDownMotionY;
362 mDragView.setTranslationX(x);
363 mDragView.setTranslationY(y);
364
365 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
366 }
367
368 public void setMinScale(float f) {
369 mMinScale = f;
370 requestLayout();
371 }
372
373 @Override
374 public void setScaleX(float scaleX) {
375 super.setScaleX(scaleX);
376 if (isReordering(true)) {
377 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
378 mLastMotionX = p[0];
379 mLastMotionY = p[1];
380 updateDragViewTranslationDuringDrag();
381 }
382 }
383
384 // Convenience methods to get the actual width/height of the PagedView (since it is measured
385 // to be larger to account for the minimum possible scale)
386 int getViewportWidth() {
387 return mViewport.width();
388 }
389 int getViewportHeight() {
390 return mViewport.height();
391 }
392
393 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
394 // PagedView both horizontally and vertically
395 int getViewportOffsetX() {
396 return (getMeasuredWidth() - getViewportWidth()) / 2;
397 }
398
399 int getViewportOffsetY() {
400 return (getMeasuredHeight() - getViewportHeight()) / 2;
401 }
402
Winson Chung86f77532010-08-24 11:08:22 -0700403 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
404 mPageSwitchListener = pageSwitchListener;
405 if (mPageSwitchListener != null) {
406 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700407 }
408 }
409
410 /**
Winson Chung52aee602013-01-30 12:01:02 -0800411 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
412 */
413 public boolean isLayoutRtl() {
414 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
415 }
416
417 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700418 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
419 * out pages.
420 */
421 protected void setDataIsReady() {
422 mIsDataReady = true;
423 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700424
Winson Chungf0ea4d32011-06-06 14:27:16 -0700425 protected boolean isDataReady() {
426 return mIsDataReady;
427 }
428
429 /**
Winson Chung86f77532010-08-24 11:08:22 -0700430 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700431 *
Winson Chung86f77532010-08-24 11:08:22 -0700432 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700433 */
Winson Chung86f77532010-08-24 11:08:22 -0700434 int getCurrentPage() {
435 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700436 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700437
Winson Chung360e63f2012-04-27 13:48:05 -0700438 int getNextPage() {
439 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
440 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700441
Winson Chung86f77532010-08-24 11:08:22 -0700442 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700443 return getChildCount();
444 }
445
Winson Chung86f77532010-08-24 11:08:22 -0700446 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700447 return getChildAt(index);
448 }
449
Adam Cohenae4f1552011-10-20 00:15:42 -0700450 protected int indexToPage(int index) {
451 return index;
452 }
453
Winson Chung321e9ee2010-08-09 13:37:56 -0700454 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800455 * Updates the scroll of the current page immediately to its final scroll position. We use this
456 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
457 * the previous tab page.
458 */
459 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700460 // If the current page is invalid, just reset the scroll position to zero
461 int newX = 0;
462 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
463 int offset = getChildOffset(mCurrentPage);
464 int relOffset = getRelativeChildOffset(mCurrentPage);
465 newX = offset - relOffset;
466 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800467 scrollTo(newX, 0);
468 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800469 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800470 }
471
472 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700473 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
474 * ends, {@link #resumeScrolling()} should be called, along with
475 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
476 */
477 void pauseScrolling() {
478 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700479 }
480
481 /**
482 * Enables scrolling again.
483 * @see #pauseScrolling()
484 */
485 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700486 }
487 /**
Winson Chung86f77532010-08-24 11:08:22 -0700488 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700489 */
Winson Chung86f77532010-08-24 11:08:22 -0700490 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800491 if (!mScroller.isFinished()) {
492 mScroller.abortAnimation();
493 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800494 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
495 // the default
496 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800497 return;
498 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700499
Adam Cohene61a9a22013-06-11 15:45:31 -0700500 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700501 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700502 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800503 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700504 }
505
Michael Jurka0142d492010-08-25 17:46:15 -0700506 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700507 if (mPageSwitchListener != null) {
508 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700509 }
Winson Chungd2be3812013-07-16 11:11:32 -0700510
511 // Update the page indicator (when we aren't reordering)
512 if (mPageIndicator != null && !isReordering(false)) {
513 mPageIndicator.setActiveMarker(getNextPage());
514 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700515 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800516 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700517 if (!mIsPageMoving) {
518 mIsPageMoving = true;
519 onPageBeginMoving();
520 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700521 }
522
Michael Jurkace7e05f2011-02-01 22:02:35 -0800523 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700524 if (mIsPageMoving) {
525 mIsPageMoving = false;
526 onPageEndMoving();
527 }
Michael Jurka0142d492010-08-25 17:46:15 -0700528 }
529
Adam Cohen26976d92011-03-22 15:33:33 -0700530 protected boolean isPageMoving() {
531 return mIsPageMoving;
532 }
533
Michael Jurka0142d492010-08-25 17:46:15 -0700534 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700535 protected void onPageBeginMoving() {
536 }
537
538 // a method that subclasses can override to add behavior
539 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700540 }
541
Winson Chung321e9ee2010-08-09 13:37:56 -0700542 /**
Winson Chung86f77532010-08-24 11:08:22 -0700543 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700544 *
545 * @param l The listener used to respond to long clicks.
546 */
547 @Override
548 public void setOnLongClickListener(OnLongClickListener l) {
549 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700550 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700551 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700552 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700553 }
554 }
555
556 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800557 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700558 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800559 }
560
561 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700562 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700563 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800564 mUnboundedScrollX = x;
565
Adam Cohen0ffac432013-07-10 11:19:26 -0700566 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
567 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
568 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800569 super.scrollTo(0, y);
570 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700571 if (isRtl) {
572 overScroll(x - mMaxScrollX);
573 } else {
574 overScroll(x);
575 }
Adam Cohen68d73932010-11-15 10:50:58 -0800576 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700577 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800578 super.scrollTo(mMaxScrollX, y);
579 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700580 if (isRtl) {
581 overScroll(x);
582 } else {
583 overScroll(x - mMaxScrollX);
584 }
Adam Cohen68d73932010-11-15 10:50:58 -0800585 }
586 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800587 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800588 super.scrollTo(x, y);
589 }
590
Michael Jurka0142d492010-08-25 17:46:15 -0700591 mTouchX = x;
592 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700593
594 // Update the last motion events when scrolling
595 if (isReordering(true)) {
596 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
597 mLastMotionX = p[0];
598 mLastMotionY = p[1];
599 updateDragViewTranslationDuringDrag();
600 }
Michael Jurka0142d492010-08-25 17:46:15 -0700601 }
602
603 // we moved this functionality to a helper function so SmoothPagedView can reuse it
604 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700605 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700606 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700607 if (getScrollX() != mScroller.getCurrX()
608 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700609 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700610 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
611 }
Michael Jurka0142d492010-08-25 17:46:15 -0700612 invalidate();
613 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700614 } else if (mNextPage != INVALID_PAGE) {
615 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700616 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700617 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700618
Adam Cohen73aa9752010-11-24 16:26:58 -0800619 // We don't want to trigger a page end moving unless the page has settled
620 // and the user has stopped scrolling
621 if (mTouchState == TOUCH_STATE_REST) {
622 pageEndMoving();
623 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700624
Adam Cohen7d30a372013-07-01 17:03:59 -0700625 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700626 // Notify the user when the page changes
627 AccessibilityManager accessibilityManager = (AccessibilityManager)
628 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
629 if (accessibilityManager.isEnabled()) {
630 AccessibilityEvent ev =
631 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
632 ev.getText().add(getCurrentPageDescription());
633 sendAccessibilityEventUnchecked(ev);
634 }
Michael Jurka0142d492010-08-25 17:46:15 -0700635 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700636 }
Michael Jurka0142d492010-08-25 17:46:15 -0700637 return false;
638 }
639
640 @Override
641 public void computeScroll() {
642 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700643 }
644
Adam Cohen7d30a372013-07-01 17:03:59 -0700645 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
646 return mTopAlignPageWhenShrinkingForBouncer;
647 }
648
Winson Chung321e9ee2010-08-09 13:37:56 -0700649 @Override
650 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700651 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700652 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
653 return;
654 }
655
Adam Cohen7d30a372013-07-01 17:03:59 -0700656 // We measure the dimensions of the PagedView to be larger than the pages so that when we
657 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700658 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
659 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
660 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700661 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700662 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
663 // viewport, we can be at most one and a half screens offset once we scale down
664 DisplayMetrics dm = getResources().getDisplayMetrics();
665 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
666 int parentWidthSize = (int) (1.5f * maxSize);
667 int parentHeightSize = maxSize;
668 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
669 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
670 mViewport.set(0, 0, widthSize, heightSize);
671
672 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
673 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
674 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700675 }
676
Winson Chung8aad6102012-05-11 16:27:49 -0700677 // Return early if we aren't given a proper dimension
678 if (widthSize <= 0 || heightSize <= 0) {
679 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
680 return;
681 }
682
Adam Lesinski6b879f02010-11-04 16:15:23 -0700683 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
684 * of the All apps view on XLarge displays to not take up more space then it needs. Width
685 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
686 * each page to have the same width.
687 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700688 final int verticalPadding = getPaddingTop() + getPaddingBottom();
689 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700690
691 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700692 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700693 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700694 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
695 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
696 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
697 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700698 final int childCount = getChildCount();
699 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700700 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700701 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700702 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
703
704 int childWidthMode;
705 if (lp.width == LayoutParams.WRAP_CONTENT) {
706 childWidthMode = MeasureSpec.AT_MOST;
707 } else {
708 childWidthMode = MeasureSpec.EXACTLY;
709 }
710
711 int childHeightMode;
712 if (lp.height == LayoutParams.WRAP_CONTENT) {
713 childHeightMode = MeasureSpec.AT_MOST;
714 } else {
715 childHeightMode = MeasureSpec.EXACTLY;
716 }
717
718 final int childWidthMeasureSpec =
Winson Chungea359c62011-08-03 17:06:35 -0700719 MeasureSpec.makeMeasureSpec(widthSize - horizontalPadding, childWidthMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700720 final int childHeightMeasureSpec =
Adam Lesinski6b879f02010-11-04 16:15:23 -0700721 MeasureSpec.makeMeasureSpec(heightSize - verticalPadding, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700722
723 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700724 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700725 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700726
Winson Chung8aad6102012-05-11 16:27:49 -0700727 // We can't call getChildOffset/getRelativeChildOffset until we set the measured dimensions.
728 // We also wait until we set the measured dimensions before flushing the cache as well, to
729 // ensure that the cache is filled with good values.
730 invalidateCachedOffsets();
731
Adam Cohenaccfd562013-07-12 14:40:40 -0700732 if (mScroller.isFinished() && mChildCountOnLastMeasure != getChildCount() &&
733 !mDeferringForDelete) {
734 setCurrentPage(getNextPage());
Adam Cohene61a9a22013-06-11 15:45:31 -0700735 }
736 mChildCountOnLastMeasure = getChildCount();
737
Winson Chunga128a7b2012-04-30 15:23:15 -0700738 if (childCount > 0) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700739 if (DEBUG) Log.d(TAG, "getRelativeChildOffset(): " + getViewportWidth() + ", "
Winson Chunga128a7b2012-04-30 15:23:15 -0700740 + getChildWidth(0));
741
742 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700743 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700744 // The gap between pages in the PagedView should be equal to the gap from the page
745 // to the edge of the screen (so it is not visible in the current screen). To
746 // account for unequal padding on each side of the paged view, we take the maximum
747 // of the left/right gap and use that as the gap between each page.
748 int offset = getRelativeChildOffset(0);
749 int spacing = Math.max(offset, widthSize - offset -
750 getChildAt(0).getMeasuredWidth());
751 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700752 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700753 }
754 }
755
Adam Cohenfaa28302010-11-19 12:02:18 -0800756 if (childCount > 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700757 final int index = isLayoutRtl() ? 0 : childCount - 1;
758 mMaxScrollX = getChildOffset(index) - getRelativeChildOffset(index);
Adam Cohenfaa28302010-11-19 12:02:18 -0800759 } else {
760 mMaxScrollX = 0;
761 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700762 }
763
Adam Cohen60b07122011-11-14 17:26:06 -0800764 public void setPageSpacing(int pageSpacing) {
765 mPageSpacing = pageSpacing;
766 invalidateCachedOffsets();
767 }
768
Winson Chung321e9ee2010-08-09 13:37:56 -0700769 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700770 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700771 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700772 return;
773 }
774
Winson Chung785d2eb2011-04-14 16:08:02 -0700775 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700776 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700777
Adam Cohen7d30a372013-07-01 17:03:59 -0700778 int offsetX = getViewportOffsetX();
779 int offsetY = getViewportOffsetY();
780
781 // Update the viewport offsets
782 mViewport.offset(offsetX, offsetY);
783
Adam Cohen0ffac432013-07-10 11:19:26 -0700784 final boolean isRtl = isLayoutRtl();
785
786 final int startIndex = isRtl ? childCount - 1 : 0;
787 final int endIndex = isRtl ? -1 : childCount;
788 final int delta = isRtl ? -1 : 1;
789
Adam Cohen7d30a372013-07-01 17:03:59 -0700790 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohen0ffac432013-07-10 11:19:26 -0700791 int childLeft = offsetX + getRelativeChildOffset(startIndex);
792 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700793 final View child = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -0700794 int childTop = offsetY + getPaddingTop();
795 if (mCenterPagesVertically) {
796 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
797 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700798 if (child.getVisibility() != View.GONE) {
Michael Jurkad3ef3062010-11-23 16:23:58 -0800799 final int childWidth = getScaledMeasuredWidth(child);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700800 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800801
Winson Chung785d2eb2011-04-14 16:08:02 -0700802 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700803 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800804 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700805 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700806 }
807 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700808
809 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
810 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800811 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700812 setHorizontalScrollBarEnabled(true);
813 mFirstLayout = false;
814 }
Winson Chunge3193b92010-09-10 11:44:42 -0700815 }
816
Adam Cohenf34bab52010-09-30 14:11:56 -0700817 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700818 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
819
820 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700821 for (int i = 0; i < getChildCount(); i++) {
822 View child = getChildAt(i);
823 if (child != null) {
824 float scrollProgress = getScrollProgress(screenCenter, child, i);
825 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800826 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700827 }
828 }
829 invalidate();
830 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700831 }
832
Winson Chunge3193b92010-09-10 11:44:42 -0700833 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700834 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700835 // Update the page indicator, we don't update the page indicator as we
836 // add/remove pages
837 if (mPageIndicator != null && !isReordering(false)) {
838 mPageIndicator.addMarker(indexOfChild(child));
839 }
840
Adam Cohen2591f6a2011-10-25 14:36:40 -0700841 // This ensures that when children are added, they get the correct transforms / alphas
842 // in accordance with any scroll effects.
843 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700844 mRecomputePageSpacing = true;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700845 invalidate();
Adam Cohen25b29952011-11-02 14:49:06 -0700846 invalidateCachedOffsets();
Adam Cohen2591f6a2011-10-25 14:36:40 -0700847 }
848
Michael Jurka8b805b12012-04-18 14:23:14 -0700849 @Override
850 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700851 mForceScreenScrolled = true;
852 invalidate();
853 invalidateCachedOffsets();
Michael Jurka8b805b12012-04-18 14:23:14 -0700854 }
855
Winson Chungd2be3812013-07-16 11:11:32 -0700856 private void removeMarkerForView(int index) {
857 // Update the page indicator, we don't update the page indicator as we
858 // add/remove pages
859 if (mPageIndicator != null && !isReordering(false)) {
860 mPageIndicator.removeMarker(index);
861 }
862 }
863
864 @Override
865 public void removeView(View v) {
866 // XXX: We should find a better way to hook into this before the view
867 // gets removed form its parent...
868 removeMarkerForView(indexOfChild(v));
869 super.removeView(v);
870 }
871 @Override
872 public void removeViewInLayout(View v) {
873 // XXX: We should find a better way to hook into this before the view
874 // gets removed form its parent...
875 removeMarkerForView(indexOfChild(v));
876 super.removeViewInLayout(v);
877 }
878 @Override
879 public void removeViewAt(int index) {
880 // XXX: We should find a better way to hook into this before the view
881 // gets removed form its parent...
882 removeViewAt(index);
883 super.removeViewAt(index);
884 }
885 @Override
886 public void removeAllViewsInLayout() {
887 // Update the page indicator, we don't update the page indicator as we
888 // add/remove pages
889 if (mPageIndicator != null) {
890 mPageIndicator.removeAllMarkers();
891 }
892
893 super.removeAllViewsInLayout();
894 }
895
Adam Cohen73894962011-10-31 13:17:17 -0700896 protected void invalidateCachedOffsets() {
897 int count = getChildCount();
Adam Cohen25b29952011-11-02 14:49:06 -0700898 if (count == 0) {
899 mChildOffsets = null;
900 mChildRelativeOffsets = null;
901 mChildOffsetsWithLayoutScale = null;
902 return;
903 }
Adam Cohen73894962011-10-31 13:17:17 -0700904
905 mChildOffsets = new int[count];
906 mChildRelativeOffsets = new int[count];
907 mChildOffsetsWithLayoutScale = new int[count];
908 for (int i = 0; i < count; i++) {
909 mChildOffsets[i] = -1;
910 mChildRelativeOffsets[i] = -1;
911 mChildOffsetsWithLayoutScale[i] = -1;
912 }
913 }
914
915 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700916 if (index < 0 || index > getChildCount() - 1) return 0;
917
Adam Cohen0ffac432013-07-10 11:19:26 -0700918 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700919 int[] childOffsets = Float.compare(mLayoutScale, 1f) == 0 ?
920 mChildOffsets : mChildOffsetsWithLayoutScale;
921
922 if (childOffsets != null && childOffsets[index] != -1) {
923 return childOffsets[index];
924 } else {
925 if (getChildCount() == 0)
926 return 0;
927
Adam Cohen0ffac432013-07-10 11:19:26 -0700928
929 final int startIndex = isRtl ? getChildCount() - 1 : 0;
930 final int endIndex = isRtl ? index : index;
931 final int delta = isRtl ? -1 : 1;
932
933 int offset = getRelativeChildOffset(startIndex);
934 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen73894962011-10-31 13:17:17 -0700935 offset += getScaledMeasuredWidth(getPageAt(i)) + mPageSpacing;
936 }
937 if (childOffsets != null) {
938 childOffsets[index] = offset;
939 }
940 return offset;
941 }
942 }
943
944 protected int getRelativeChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700945 if (index < 0 || index > getChildCount() - 1) return 0;
946
Adam Cohen73894962011-10-31 13:17:17 -0700947 if (mChildRelativeOffsets != null && mChildRelativeOffsets[index] != -1) {
948 return mChildRelativeOffsets[index];
949 } else {
Michael Jurka8b805b12012-04-18 14:23:14 -0700950 final int padding = getPaddingLeft() + getPaddingRight();
951 final int offset = getPaddingLeft() +
Adam Cohen7d30a372013-07-01 17:03:59 -0700952 (getViewportWidth() - padding - getChildWidth(index)) / 2;
Adam Cohen73894962011-10-31 13:17:17 -0700953 if (mChildRelativeOffsets != null) {
954 mChildRelativeOffsets[index] = offset;
955 }
956 return offset;
957 }
958 }
959
Adam Cohen73894962011-10-31 13:17:17 -0700960 protected int getScaledMeasuredWidth(View child) {
961 // This functions are called enough times that it actually makes a difference in the
962 // profiler -- so just inline the max() here
963 final int measuredWidth = child.getMeasuredWidth();
964 final int minWidth = mMinimumWidth;
965 final int maxWidth = (minWidth > measuredWidth) ? minWidth : measuredWidth;
966 return (int) (maxWidth * mLayoutScale + 0.5f);
967 }
968
Adam Cohen7d30a372013-07-01 17:03:59 -0700969 void boundByReorderablePages(boolean isReordering, int[] range) {
970 // Do nothing
971 }
972
973 // TODO: Fix this
Michael Jurkadde558b2011-11-09 22:09:06 -0800974 protected void getVisiblePages(int[] range) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700975 range[0] = 0;
976 range[1] = getPageCount() - 1;
977
978 /*
Michael Jurka0142d492010-08-25 17:46:15 -0700979 final int pageCount = getChildCount();
Michael Jurka4ff7d792012-04-02 03:46:50 -0700980
Michael Jurkac4fb9172010-09-02 17:19:20 -0700981 if (pageCount > 0) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700982 final int screenWidth = getViewportWidth();
983 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -0700984 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -0700985 int offsetX = getViewportOffsetX() + getScrollX();
Michael Jurka47f74742012-03-02 13:39:13 -0800986 View currPage = getPageAt(leftScreen);
Adam Cohen7d30a372013-07-01 17:03:59 -0700987 while (leftScreen < pageCount - 1 &&
Michael Jurka8b805b12012-04-18 14:23:14 -0700988 currPage.getX() + currPage.getWidth() -
Adam Cohen7d30a372013-07-01 17:03:59 -0700989 currPage.getPaddingRight() < offsetX) {
990 leftScreen++;
Michael Jurka47f74742012-03-02 13:39:13 -0800991 currPage = getPageAt(leftScreen);
Michael Jurkac4fb9172010-09-02 17:19:20 -0700992 }
993 rightScreen = leftScreen;
Adam Cohen7d30a372013-07-01 17:03:59 -0700994 currPage = getPageAt(rightScreen + 1);
995 while (rightScreen < pageCount - 1 &&
996 currPage.getX() - currPage.getPaddingLeft() < offsetX + screenWidth) {
997 rightScreen++;
998 currPage = getPageAt(rightScreen + 1);
Michael Jurkac4fb9172010-09-02 17:19:20 -0700999 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001000
1001 // TEMP: this is a hacky way to ensure that animations to new pages are not clipped
1002 // because we don't draw them while scrolling?
1003 range[0] = Math.max(0, leftScreen - 1);
1004 range[1] = Math.min(rightScreen + 1, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001005 } else {
1006 range[0] = -1;
1007 range[1] = -1;
1008 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001009 */
Michael Jurkadde558b2011-11-09 22:09:06 -08001010 }
1011
Michael Jurka920d7f42012-05-14 16:29:55 -07001012 protected boolean shouldDrawChild(View child) {
1013 return child.getAlpha() > 0;
1014 }
1015
Michael Jurkadde558b2011-11-09 22:09:06 -08001016 @Override
1017 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001018 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001019 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1020 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001021 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001022
1023 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001024 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1025 // set it for the next frame
1026 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001027 screenScrolled(screenCenter);
1028 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001029 }
1030
1031 // Find out which screens are visible; as an optimization we only call draw on them
1032 final int pageCount = getChildCount();
1033 if (pageCount > 0) {
1034 getVisiblePages(mTempVisiblePagesRange);
1035 final int leftScreen = mTempVisiblePagesRange[0];
1036 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001037 if (leftScreen != -1 && rightScreen != -1) {
1038 final long drawingTime = getDrawingTime();
1039 // Clip to the bounds
1040 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001041 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1042 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001043
Adam Cohen7d30a372013-07-01 17:03:59 -07001044 // Draw all the children, leaving the drag view for last
1045 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001046 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001047 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001048 if (mForceDrawAllChildrenNextFrame ||
1049 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001050 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001051 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001052 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001053 // Draw the drag view on top (if there is one)
1054 if (mDragView != null) {
1055 drawChild(canvas, mDragView, drawingTime);
1056 }
1057
Michael Jurka5e368ff2012-05-14 23:13:15 -07001058 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001059 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001060 }
Michael Jurka0142d492010-08-25 17:46:15 -07001061 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001062 }
1063
1064 @Override
1065 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001066 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001067 if (page != mCurrentPage || !mScroller.isFinished()) {
1068 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001069 return true;
1070 }
1071 return false;
1072 }
1073
1074 @Override
1075 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001076 int focusablePage;
1077 if (mNextPage != INVALID_PAGE) {
1078 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001079 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001080 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001081 }
Winson Chung86f77532010-08-24 11:08:22 -07001082 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001083 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001084 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001085 }
1086 return false;
1087 }
1088
1089 @Override
1090 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001091 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001092 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001093 if (getCurrentPage() > 0) {
1094 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001095 return true;
1096 }
1097 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001098 if (getCurrentPage() < getPageCount() - 1) {
1099 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001100 return true;
1101 }
1102 }
1103 return super.dispatchUnhandledMove(focused, direction);
1104 }
1105
1106 @Override
1107 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001108 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001109 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001110 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001111 }
1112 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001113 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001114 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001115 }
1116 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001117 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001118 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001119 }
1120 }
1121 }
1122
1123 /**
1124 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001125 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001126 *
Winson Chung86f77532010-08-24 11:08:22 -07001127 * This happens when live folders requery, and if they're off page, they
1128 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001129 */
1130 @Override
1131 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001132 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001133 View v = focused;
1134 while (true) {
1135 if (v == current) {
1136 super.focusableViewAvailable(focused);
1137 return;
1138 }
1139 if (v == this) {
1140 return;
1141 }
1142 ViewParent parent = v.getParent();
1143 if (parent instanceof View) {
1144 v = (View)v.getParent();
1145 } else {
1146 return;
1147 }
1148 }
1149 }
1150
1151 /**
1152 * {@inheritDoc}
1153 */
1154 @Override
1155 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1156 if (disallowIntercept) {
1157 // We need to make sure to cancel our long press if
1158 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001159 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001160 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001161 }
1162 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1163 }
1164
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001165 /**
1166 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1167 */
1168 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001169 if (isLayoutRtl()) {
1170 return (x > (getViewportOffsetX() + getViewportWidth() -
1171 getRelativeChildOffset(mCurrentPage) + mPageSpacing));
1172 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001173 return (x < getViewportOffsetX() + getRelativeChildOffset(mCurrentPage) - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001174 }
1175
1176 /**
1177 * Return true if a tap at (x, y) should trigger a flip to the next page.
1178 */
1179 protected boolean hitsNextPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001180 if (isLayoutRtl()) {
1181 return (x < getViewportOffsetX() + getRelativeChildOffset(mCurrentPage) - mPageSpacing);
1182 }
1183 return (x > (getViewportOffsetX() + getViewportWidth() -
1184 getRelativeChildOffset(mCurrentPage) + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001185 }
Winson Chung52aee602013-01-30 12:01:02 -08001186
Adam Cohen7d30a372013-07-01 17:03:59 -07001187 /** Returns whether x and y originated within the buffered viewport */
1188 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1189 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1190 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1191 return mTmpRect.contains(x, y);
1192 }
1193
1194 /** Returns whether x and y originated within the current page view bounds */
1195 private boolean isTouchPointInCurrentPage(int x, int y) {
1196 View v = getPageAt(getCurrentPage());
1197 if (v != null) {
1198 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1199 v.getBottom());
1200 return mTmpRect.contains(x, y);
1201 }
1202 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001203 }
1204
Winson Chung321e9ee2010-08-09 13:37:56 -07001205 @Override
1206 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001207 if (DISABLE_TOUCH_INTERACTION) {
1208 return false;
1209 }
1210
Winson Chung321e9ee2010-08-09 13:37:56 -07001211 /*
1212 * This method JUST determines whether we want to intercept the motion.
1213 * If we return true, onTouchEvent will be called and we do the actual
1214 * scrolling there.
1215 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001216 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001217
Winson Chung45e1d6e2010-11-09 17:19:49 -08001218 // Skip touch handling if there are no pages to swipe
1219 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1220
Winson Chung321e9ee2010-08-09 13:37:56 -07001221 /*
1222 * Shortcut the most recurring case: the user is in the dragging
1223 * state and he is moving his finger. We want to intercept this
1224 * motion.
1225 */
1226 final int action = ev.getAction();
1227 if ((action == MotionEvent.ACTION_MOVE) &&
1228 (mTouchState == TOUCH_STATE_SCROLLING)) {
1229 return true;
1230 }
1231
Winson Chung321e9ee2010-08-09 13:37:56 -07001232 switch (action & MotionEvent.ACTION_MASK) {
1233 case MotionEvent.ACTION_MOVE: {
1234 /*
1235 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1236 * whether the user has moved far enough from his original down touch.
1237 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001238 if (mActivePointerId != INVALID_POINTER) {
1239 determineScrollingStart(ev);
1240 break;
1241 }
1242 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1243 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1244 // i.e. fall through to the next case (don't break)
1245 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1246 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001247 }
1248
1249 case MotionEvent.ACTION_DOWN: {
1250 final float x = ev.getX();
1251 final float y = ev.getY();
1252 // Remember location of down touch
1253 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001254 mDownMotionY = y;
1255 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001256 mLastMotionX = x;
1257 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001258 float[] p = mapPointFromViewToParent(this, x, y);
1259 mParentDownMotionX = p[0];
1260 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001261 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001262 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001263 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001264
1265 // Determine if the down event is within the threshold to be an edge swipe
1266 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1267 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1268 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1269 mDownEventOnEdge = true;
1270 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001271
1272 /*
1273 * If being flinged and user touches the screen, initiate drag;
1274 * otherwise don't. mScroller.isFinished should be false when
1275 * being flinged.
1276 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001277 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001278 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1279 if (finishedScrolling) {
1280 mTouchState = TOUCH_STATE_REST;
1281 mScroller.abortAnimation();
1282 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001283 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1284 mTouchState = TOUCH_STATE_SCROLLING;
1285 } else {
1286 mTouchState = TOUCH_STATE_REST;
1287 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001288 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001289
Winson Chung86f77532010-08-24 11:08:22 -07001290 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001291 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001292 if (!DISABLE_TOUCH_SIDE_PAGES) {
1293 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1294 if (getChildCount() > 0) {
1295 if (hitsPreviousPage(x, y)) {
1296 mTouchState = TOUCH_STATE_PREV_PAGE;
1297 } else if (hitsNextPage(x, y)) {
1298 mTouchState = TOUCH_STATE_NEXT_PAGE;
1299 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001300 }
1301 }
1302 }
1303 break;
1304 }
1305
Winson Chung321e9ee2010-08-09 13:37:56 -07001306 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001307 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001308 resetTouchState();
1309 // Just intercept the touch event on up if we tap outside the strict viewport
1310 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1311 return true;
1312 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001313 break;
1314
1315 case MotionEvent.ACTION_POINTER_UP:
1316 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001317 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001318 break;
1319 }
1320
1321 /*
1322 * The only time we want to intercept motion events is if we are in the
1323 * drag mode.
1324 */
1325 return mTouchState != TOUCH_STATE_REST;
1326 }
1327
Adam Cohenf8d28232011-02-01 21:47:00 -08001328 protected void determineScrollingStart(MotionEvent ev) {
1329 determineScrollingStart(ev, 1.0f);
1330 }
1331
Winson Chung321e9ee2010-08-09 13:37:56 -07001332 /*
1333 * Determines if we should change the touch state to start scrolling after the
1334 * user moves their touch point too far.
1335 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001336 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001337 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001338 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001339 if (pointerIndex == -1) return;
1340
1341 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001342 final float x = ev.getX(pointerIndex);
1343 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001344 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1345
1346 // If we're only allowing edge swipes, we break out early if the down event wasn't
1347 // at the edge.
1348 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1349
Winson Chung321e9ee2010-08-09 13:37:56 -07001350 final int xDiff = (int) Math.abs(x - mLastMotionX);
1351 final int yDiff = (int) Math.abs(y - mLastMotionY);
1352
Adam Cohenf8d28232011-02-01 21:47:00 -08001353 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001354 boolean xPaged = xDiff > mPagingTouchSlop;
1355 boolean xMoved = xDiff > touchSlop;
1356 boolean yMoved = yDiff > touchSlop;
1357
Adam Cohenf8d28232011-02-01 21:47:00 -08001358 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001359 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001360 // Scroll if the user moved far enough along the X axis
1361 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001362 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001363 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001364 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001365 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001366 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1367 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001368 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001369 }
1370 }
1371
Adam Cohen7d30a372013-07-01 17:03:59 -07001372 protected float getMaxScrollProgress() {
1373 return 1.0f;
1374 }
1375
Adam Cohenf8d28232011-02-01 21:47:00 -08001376 protected void cancelCurrentPageLongPress() {
1377 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001378 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001379 // Try canceling the long press. It could also have been scheduled
1380 // by a distant descendant, so use the mAllowLongPress flag to block
1381 // everything
1382 final View currentPage = getPageAt(mCurrentPage);
1383 if (currentPage != null) {
1384 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001385 }
1386 }
1387 }
1388
Adam Cohen7d30a372013-07-01 17:03:59 -07001389 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1390 final int halfScreenSize = getViewportWidth() / 2;
1391
1392 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1393 screenCenter = Math.max(halfScreenSize, screenCenter);
1394
1395 return getScrollProgress(screenCenter, v, page);
1396 }
1397
Adam Cohenb5ba0972011-09-07 18:02:31 -07001398 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001399 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001400
1401 int totalDistance = getScaledMeasuredWidth(v) + mPageSpacing;
1402 int delta = screenCenter - (getChildOffset(page) -
1403 getRelativeChildOffset(page) + halfScreenSize);
1404
1405 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001406 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1407 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001408 return scrollProgress;
1409 }
1410
Adam Cohene0f66b52010-11-23 15:06:07 -08001411 // This curve determines how the effect of scrolling over the limits of the page dimishes
1412 // as the user pulls further and further from the bounds
1413 private float overScrollInfluenceCurve(float f) {
1414 f -= 1.0f;
1415 return f * f * f + 1.0f;
1416 }
1417
Adam Cohenb5ba0972011-09-07 18:02:31 -07001418 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001419 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001420
1421 // We want to reach the max over scroll effect when the user has
1422 // over scrolled half the size of the screen
1423 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1424
1425 if (f == 0) return;
1426
1427 // Clamp this factor, f, to -1 < f < 1
1428 if (Math.abs(f) >= 1) {
1429 f /= Math.abs(f);
1430 }
1431
1432 int overScrollAmount = (int) Math.round(f * screenSize);
1433 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001434 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001435 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001436 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001437 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001438 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001439 }
1440 invalidate();
1441 }
1442
1443 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001444 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001445
1446 float f = (amount / screenSize);
1447
1448 if (f == 0) return;
1449 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1450
Adam Cohen7bfc9792011-01-28 13:52:37 -08001451 // Clamp this factor, f, to -1 < f < 1
1452 if (Math.abs(f) >= 1) {
1453 f /= Math.abs(f);
1454 }
1455
Adam Cohene0f66b52010-11-23 15:06:07 -08001456 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001457 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001458 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001459 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001460 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001461 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001462 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001463 }
1464 invalidate();
1465 }
1466
Adam Cohenb5ba0972011-09-07 18:02:31 -07001467 protected void overScroll(float amount) {
1468 dampedOverScroll(amount);
1469 }
1470
Michael Jurkac5b262c2011-01-12 20:24:50 -08001471 protected float maxOverScroll() {
1472 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001473 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001474 float f = 1.0f;
1475 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1476 return OVERSCROLL_DAMP_FACTOR * f;
1477 }
1478
Winson Chung321e9ee2010-08-09 13:37:56 -07001479 @Override
1480 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001481 if (DISABLE_TOUCH_INTERACTION) {
1482 return false;
1483 }
1484
Winson Chung45e1d6e2010-11-09 17:19:49 -08001485 // Skip touch handling if there are no pages to swipe
1486 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1487
Michael Jurkab8f06722010-10-10 15:58:46 -07001488 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001489
1490 final int action = ev.getAction();
1491
1492 switch (action & MotionEvent.ACTION_MASK) {
1493 case MotionEvent.ACTION_DOWN:
1494 /*
1495 * If being flinged and user touches, stop the fling. isFinished
1496 * will be false if being flinged.
1497 */
1498 if (!mScroller.isFinished()) {
1499 mScroller.abortAnimation();
1500 }
1501
1502 // Remember where the motion event started
1503 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001504 mDownMotionY = mLastMotionY = ev.getY();
1505 mDownScrollX = getScrollX();
1506 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1507 mParentDownMotionX = p[0];
1508 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001509 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001510 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001511 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001512
1513 // Determine if the down event is within the threshold to be an edge swipe
1514 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1515 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1516 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1517 mDownEventOnEdge = true;
1518 }
1519
Michael Jurka0142d492010-08-25 17:46:15 -07001520 if (mTouchState == TOUCH_STATE_SCROLLING) {
1521 pageBeginMoving();
1522 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001523 break;
1524
1525 case MotionEvent.ACTION_MOVE:
1526 if (mTouchState == TOUCH_STATE_SCROLLING) {
1527 // Scroll to follow the motion event
1528 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001529
1530 if (pointerIndex == -1) return true;
1531
Winson Chung321e9ee2010-08-09 13:37:56 -07001532 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001533 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001534
Adam Cohenaefd4e12011-02-14 16:39:38 -08001535 mTotalMotionX += Math.abs(deltaX);
1536
Winson Chungc0844aa2011-02-02 15:25:58 -08001537 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1538 // keep the remainder because we are actually testing if we've moved from the last
1539 // scrolled position (which is discrete).
1540 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001541 mTouchX += deltaX;
1542 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1543 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001544 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001545 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001546 } else {
1547 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001548 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001549 mLastMotionX = x;
1550 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001551 } else {
1552 awakenScrollBars();
1553 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001554 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1555 // Update the last motion position
1556 mLastMotionX = ev.getX();
1557 mLastMotionY = ev.getY();
1558
1559 // Update the parent down so that our zoom animations take this new movement into
1560 // account
1561 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1562 mParentDownMotionX = pt[0];
1563 mParentDownMotionY = pt[1];
1564 updateDragViewTranslationDuringDrag();
1565
1566 // Find the closest page to the touch point
1567 final int dragViewIndex = indexOfChild(mDragView);
1568 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1569 getViewportWidth());
1570 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1571 + bufferSize);
1572 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1573 - bufferSize);
1574
1575 // Change the drag view if we are hovering over the drop target
1576 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1577 (int) mParentDownMotionX, (int) mParentDownMotionY);
1578 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1579
1580 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1581 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1582 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1583 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1584 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1585 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1586
1587 float parentX = mParentDownMotionX;
1588 int pageIndexToSnapTo = -1;
1589 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1590 pageIndexToSnapTo = dragViewIndex - 1;
1591 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1592 pageIndexToSnapTo = dragViewIndex + 1;
1593 }
1594
1595 final int pageUnderPointIndex = pageIndexToSnapTo;
1596 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1597 mTempVisiblePagesRange[0] = 0;
1598 mTempVisiblePagesRange[1] = getPageCount() - 1;
1599 boundByReorderablePages(true, mTempVisiblePagesRange);
1600 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1601 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1602 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1603 mSidePageHoverIndex = pageUnderPointIndex;
1604 mSidePageHoverRunnable = new Runnable() {
1605 @Override
1606 public void run() {
1607 // Update the down scroll position to account for the fact that the
1608 // current page is moved
1609 mDownScrollX = getChildOffset(pageUnderPointIndex)
1610 - getRelativeChildOffset(pageUnderPointIndex);
1611
1612 // Setup the scroll to the correct page before we swap the views
1613 snapToPage(pageUnderPointIndex);
1614
1615 // For each of the pages between the paged view and the drag view,
1616 // animate them from the previous position to the new position in
1617 // the layout (as a result of the drag view moving in the layout)
1618 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1619 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1620 dragViewIndex + 1 : pageUnderPointIndex;
1621 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1622 dragViewIndex - 1 : pageUnderPointIndex;
1623 for (int i = lowerIndex; i <= upperIndex; ++i) {
1624 View v = getChildAt(i);
1625 // dragViewIndex < pageUnderPointIndex, so after we remove the
1626 // drag view all subsequent views to pageUnderPointIndex will
1627 // shift down.
1628 int oldX = getViewportOffsetX() + getChildOffset(i);
1629 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1630
1631 // Animate the view translation from its old position to its new
1632 // position
1633 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1634 if (anim != null) {
1635 anim.cancel();
1636 }
1637
1638 v.setTranslationX(oldX - newX);
1639 anim = new AnimatorSet();
1640 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1641 anim.playTogether(
1642 ObjectAnimator.ofFloat(v, "translationX", 0f));
1643 anim.start();
1644 v.setTag(anim);
1645 }
1646
1647 removeView(mDragView);
1648 onRemoveView(mDragView, false);
1649 addView(mDragView, pageUnderPointIndex);
1650 onAddView(mDragView, pageUnderPointIndex);
1651 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001652 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001653 }
1654 };
1655 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1656 }
1657 } else {
1658 removeCallbacks(mSidePageHoverRunnable);
1659 mSidePageHoverIndex = -1;
1660 }
Adam Cohen564976a2010-10-13 18:52:07 -07001661 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001662 determineScrollingStart(ev);
1663 }
1664 break;
1665
1666 case MotionEvent.ACTION_UP:
1667 if (mTouchState == TOUCH_STATE_SCROLLING) {
1668 final int activePointerId = mActivePointerId;
1669 final int pointerIndex = ev.findPointerIndex(activePointerId);
1670 final float x = ev.getX(pointerIndex);
1671 final VelocityTracker velocityTracker = mVelocityTracker;
1672 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1673 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001674 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen00481b32011-11-18 12:03:48 -08001675 final int pageWidth = getScaledMeasuredWidth(getPageAt(mCurrentPage));
1676 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1677 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001678
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001679 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1680
Adam Cohen00481b32011-11-18 12:03:48 -08001681 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001682 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001683
Adam Cohenaefd4e12011-02-14 16:39:38 -08001684 // In the case that the page is moved far to one direction and then is flung
1685 // in the opposite direction, we use a threshold to determine whether we should
1686 // just return to the starting page, or if we should skip one further.
1687 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001688 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001689 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001690 returnToOriginalPage = true;
1691 }
1692
Adam Cohenaefd4e12011-02-14 16:39:38 -08001693 int finalPage;
1694 // We give flings precedence over large moves, which is why we short-circuit our
1695 // test for a large move if a fling has been registered. That is, a large
1696 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001697 final boolean isRtl = isLayoutRtl();
1698 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1699 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1700 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1701 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001702 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1703 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001704 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1705 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001706 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001707 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1708 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001709 } else {
1710 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001711 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001712 // at this point we have not moved beyond the touch slop
1713 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1714 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001715 int nextPage = Math.max(0, mCurrentPage - 1);
1716 if (nextPage != mCurrentPage) {
1717 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001718 } else {
1719 snapToDestination();
1720 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001721 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001722 // at this point we have not moved beyond the touch slop
1723 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1724 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001725 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1726 if (nextPage != mCurrentPage) {
1727 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001728 } else {
1729 snapToDestination();
1730 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001731 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1732 // Update the last motion position
1733 mLastMotionX = ev.getX();
1734 mLastMotionY = ev.getY();
1735
1736 // Update the parent down so that our zoom animations take this new movement into
1737 // account
1738 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1739 mParentDownMotionX = pt[0];
1740 mParentDownMotionY = pt[1];
1741 updateDragViewTranslationDuringDrag();
1742 boolean handledFling = false;
1743 if (!DISABLE_FLING_TO_DELETE) {
1744 // Check the velocity and see if we are flinging-to-delete
1745 PointF flingToDeleteVector = isFlingingToDelete();
1746 if (flingToDeleteVector != null) {
1747 onFlingToDelete(flingToDeleteVector);
1748 handledFling = true;
1749 }
1750 }
1751 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1752 (int) mParentDownMotionY)) {
1753 onDropToDelete();
1754 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001755 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001756 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001757 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001758
1759 // Remove the callback to wait for the side page hover timeout
1760 removeCallbacks(mSidePageHoverRunnable);
1761 // End any intermediate reordering states
1762 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001763 break;
1764
1765 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001766 if (mTouchState == TOUCH_STATE_SCROLLING) {
1767 snapToDestination();
1768 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001769 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001770 break;
1771
1772 case MotionEvent.ACTION_POINTER_UP:
1773 onSecondaryPointerUp(ev);
1774 break;
1775 }
1776
1777 return true;
1778 }
1779
Adam Cohen7d30a372013-07-01 17:03:59 -07001780 public void onFlingToDelete(View v) {}
1781 public void onRemoveView(View v, boolean deletePermanently) {}
1782 public void onRemoveViewAnimationCompleted() {}
1783 public void onAddView(View v, int index) {}
1784
1785 private void resetTouchState() {
1786 releaseVelocityTracker();
1787 endReordering();
1788 mTouchState = TOUCH_STATE_REST;
1789 mActivePointerId = INVALID_POINTER;
1790 mDownEventOnEdge = false;
1791 }
1792
1793 protected void onUnhandledTap(MotionEvent ev) {}
1794
Winson Chung185d7162011-02-28 13:47:29 -08001795 @Override
1796 public boolean onGenericMotionEvent(MotionEvent event) {
1797 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1798 switch (event.getAction()) {
1799 case MotionEvent.ACTION_SCROLL: {
1800 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1801 final float vscroll;
1802 final float hscroll;
1803 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1804 vscroll = 0;
1805 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1806 } else {
1807 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1808 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1809 }
1810 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001811 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1812 : (hscroll > 0 || vscroll > 0);
1813 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001814 scrollRight();
1815 } else {
1816 scrollLeft();
1817 }
1818 return true;
1819 }
1820 }
1821 }
1822 }
1823 return super.onGenericMotionEvent(event);
1824 }
1825
Michael Jurkab8f06722010-10-10 15:58:46 -07001826 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1827 if (mVelocityTracker == null) {
1828 mVelocityTracker = VelocityTracker.obtain();
1829 }
1830 mVelocityTracker.addMovement(ev);
1831 }
1832
1833 private void releaseVelocityTracker() {
1834 if (mVelocityTracker != null) {
1835 mVelocityTracker.recycle();
1836 mVelocityTracker = null;
1837 }
1838 }
1839
Winson Chung321e9ee2010-08-09 13:37:56 -07001840 private void onSecondaryPointerUp(MotionEvent ev) {
1841 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1842 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1843 final int pointerId = ev.getPointerId(pointerIndex);
1844 if (pointerId == mActivePointerId) {
1845 // This was our active pointer going up. Choose a new
1846 // active pointer and adjust accordingly.
1847 // TODO: Make this decision more intelligent.
1848 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1849 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1850 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001851 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001852 mActivePointerId = ev.getPointerId(newPointerIndex);
1853 if (mVelocityTracker != null) {
1854 mVelocityTracker.clear();
1855 }
1856 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001857 }
1858
Winson Chung321e9ee2010-08-09 13:37:56 -07001859 @Override
1860 public void requestChildFocus(View child, View focused) {
1861 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001862 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001863 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001864 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001865 }
1866 }
1867
Winson Chunge3193b92010-09-10 11:44:42 -07001868 protected int getChildIndexForRelativeOffset(int relativeOffset) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001869 final boolean isRtl = isLayoutRtl();
Winson Chunge3193b92010-09-10 11:44:42 -07001870 final int childCount = getChildCount();
Adam Cohen9c4949e2010-10-05 12:27:22 -07001871 int left;
1872 int right;
Adam Cohen0ffac432013-07-10 11:19:26 -07001873 final int startIndex = isRtl ? childCount - 1 : 0;
1874 final int endIndex = isRtl ? -1 : childCount;
1875 final int delta = isRtl ? -1 : 1;
1876 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen9c4949e2010-10-05 12:27:22 -07001877 left = getRelativeChildOffset(i);
Adam Cohen22f823d2011-09-01 17:22:18 -07001878 right = (left + getScaledMeasuredWidth(getPageAt(i)));
Winson Chunge3193b92010-09-10 11:44:42 -07001879 if (left <= relativeOffset && relativeOffset <= right) {
1880 return i;
1881 }
Winson Chunge3193b92010-09-10 11:44:42 -07001882 }
1883 return -1;
1884 }
1885
Winson Chung1908d072011-02-24 18:09:44 -08001886 protected int getChildWidth(int index) {
Winson Chung63257c12011-05-05 17:06:13 -07001887 // This functions are called enough times that it actually makes a difference in the
1888 // profiler -- so just inline the max() here
Adam Cohen22f823d2011-09-01 17:22:18 -07001889 final int measuredWidth = getPageAt(index).getMeasuredWidth();
Winson Chung63257c12011-05-05 17:06:13 -07001890 final int minWidth = mMinimumWidth;
1891 return (minWidth > measuredWidth) ? minWidth : measuredWidth;
Winson Chung1908d072011-02-24 18:09:44 -08001892 }
1893
Adam Cohen7d30a372013-07-01 17:03:59 -07001894 int getPageNearestToPoint(float x) {
1895 int index = 0;
1896 for (int i = 0; i < getChildCount(); ++i) {
1897 if (x < getChildAt(i).getRight() - getScrollX()) {
1898 return index;
1899 } else {
1900 index++;
1901 }
1902 }
1903 return Math.min(index, getChildCount() - 1);
1904 }
1905
Adam Cohend19d3ca2010-09-15 14:43:42 -07001906 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001907 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001908 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001909 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001910 final int childCount = getChildCount();
1911 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001912 View layout = (View) getPageAt(i);
Michael Jurkad3ef3062010-11-23 16:23:58 -08001913 int childWidth = getScaledMeasuredWidth(layout);
Winson Chung321e9ee2010-08-09 13:37:56 -07001914 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001915 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001916 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1917 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1918 minDistanceFromScreenCenter = distanceFromScreenCenter;
1919 minDistanceFromScreenCenterIndex = i;
1920 }
1921 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001922 return minDistanceFromScreenCenterIndex;
1923 }
1924
1925 protected void snapToDestination() {
1926 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001927 }
1928
Adam Cohene0f66b52010-11-23 15:06:07 -08001929 private static class ScrollInterpolator implements Interpolator {
1930 public ScrollInterpolator() {
1931 }
1932
1933 public float getInterpolation(float t) {
1934 t -= 1.0f;
1935 return t*t*t*t*t + 1;
1936 }
1937 }
1938
1939 // We want the duration of the page snap animation to be influenced by the distance that
1940 // the screen has to travel, however, we don't want this duration to be effected in a
1941 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1942 // of travel has on the overall snap duration.
1943 float distanceInfluenceForSnapDuration(float f) {
1944 f -= 0.5f; // center the values about 0.
1945 f *= 0.3f * Math.PI / 2.0f;
1946 return (float) Math.sin(f);
1947 }
1948
Michael Jurka0142d492010-08-25 17:46:15 -07001949 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001950 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001951 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001952
Winson Chung785d2eb2011-04-14 16:08:02 -07001953 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage));
1954 if (DEBUG) Log.d(TAG, "snapToPageWithVelocity.getRelativeChildOffset(): "
Adam Cohen7d30a372013-07-01 17:03:59 -07001955 + getViewportWidth() + ", " + getChildWidth(whichPage));
Adam Cohene0f66b52010-11-23 15:06:07 -08001956 final int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
1957 int delta = newX - mUnboundedScrollX;
1958 int duration = 0;
1959
Adam Cohen265b9a62011-12-07 14:37:18 -08001960 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001961 // If the velocity is low enough, then treat this more as an automatic page advance
1962 // as opposed to an apparent physical response to flinging
1963 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1964 return;
1965 }
1966
1967 // Here we compute a "distance" that will be used in the computation of the overall
1968 // snap duration. This is a function of the actual distance that needs to be traveled;
1969 // we keep this value close to half screen size in order to reduce the variance in snap
1970 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001971 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001972 float distance = halfScreenSize + halfScreenSize *
1973 distanceInfluenceForSnapDuration(distanceRatio);
1974
1975 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001976 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001977
1978 // we want the page's snap velocity to approximately match the velocity at which the
1979 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001980 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1981 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001982
1983 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001984 }
1985
1986 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001987 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001988 }
1989
Adam Cohen7d30a372013-07-01 17:03:59 -07001990 protected void snapToPageImmediately(int whichPage) {
1991 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1992 }
1993
Michael Jurka0142d492010-08-25 17:46:15 -07001994 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001995 snapToPage(whichPage, duration, false);
1996 }
1997
1998 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07001999 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002000
Winson Chung785d2eb2011-04-14 16:08:02 -07002001 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage));
Adam Cohen7d30a372013-07-01 17:03:59 -07002002 if (DEBUG) Log.d(TAG, "snapToPage.getRelativeChildOffset(): " + getViewportWidth() + ", "
Winson Chung785d2eb2011-04-14 16:08:02 -07002003 + getChildWidth(whichPage));
Winson Chung86f77532010-08-24 11:08:22 -07002004 int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002005 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002006 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002007 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002008 }
2009
2010 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002011 snapToPage(whichPage, delta, duration, false);
2012 }
Michael Jurka0142d492010-08-25 17:46:15 -07002013
Adam Cohen7d30a372013-07-01 17:03:59 -07002014 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2015 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002016 View focusedChild = getFocusedChild();
2017 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002018 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002019 focusedChild.clearFocus();
2020 }
2021
2022 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002023 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002024 if (immediate) {
2025 duration = 0;
2026 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002027 duration = Math.abs(delta);
2028 }
2029
2030 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002031 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002032
Michael Jurka0142d492010-08-25 17:46:15 -07002033 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002034
2035 // Trigger a compute() to finish switching pages if necessary
2036 if (immediate) {
2037 computeScroll();
2038 }
2039
2040 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002041 invalidate();
2042 }
2043
Winson Chung321e9ee2010-08-09 13:37:56 -07002044 public void scrollLeft() {
2045 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002046 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002047 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002048 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002049 }
2050 }
2051
2052 public void scrollRight() {
2053 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002054 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002055 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002056 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002057 }
2058 }
2059
Winson Chung86f77532010-08-24 11:08:22 -07002060 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002061 int result = -1;
2062 if (v != null) {
2063 ViewParent vp = v.getParent();
2064 int count = getChildCount();
2065 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002066 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002067 return i;
2068 }
2069 }
2070 }
2071 return result;
2072 }
2073
2074 /**
2075 * @return True is long presses are still allowed for the current touch
2076 */
2077 public boolean allowLongPress() {
2078 return mAllowLongPress;
2079 }
2080
Michael Jurka0142d492010-08-25 17:46:15 -07002081 /**
2082 * Set true to allow long-press events to be triggered, usually checked by
2083 * {@link Launcher} to accept or block dpad-initiated long-presses.
2084 */
2085 public void setAllowLongPress(boolean allowLongPress) {
2086 mAllowLongPress = allowLongPress;
2087 }
2088
Winson Chung321e9ee2010-08-09 13:37:56 -07002089 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002090 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002091
2092 SavedState(Parcelable superState) {
2093 super(superState);
2094 }
2095
2096 private SavedState(Parcel in) {
2097 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002098 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002099 }
2100
2101 @Override
2102 public void writeToParcel(Parcel out, int flags) {
2103 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002104 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002105 }
2106
2107 public static final Parcelable.Creator<SavedState> CREATOR =
2108 new Parcelable.Creator<SavedState>() {
2109 public SavedState createFromParcel(Parcel in) {
2110 return new SavedState(in);
2111 }
2112
2113 public SavedState[] newArray(int size) {
2114 return new SavedState[size];
2115 }
2116 };
2117 }
2118
Winson Chungf314b0e2011-08-16 11:54:27 -07002119 protected void loadAssociatedPages(int page) {
2120 loadAssociatedPages(page, false);
2121 }
2122 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002123 if (mContentIsRefreshable) {
2124 final int count = getChildCount();
2125 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002126 int lowerPageBound = getAssociatedLowerPageBound(page);
2127 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002128 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2129 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002130 // First, clear any pages that should no longer be loaded
2131 for (int i = 0; i < count; ++i) {
2132 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002133 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002134 if (layout.getPageChildCount() > 0) {
2135 layout.removeAllViewsOnPage();
2136 }
2137 mDirtyPageContent.set(i, true);
2138 }
2139 }
2140 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002141 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002142 if ((i != page) && immediateAndOnly) {
2143 continue;
2144 }
Michael Jurka0142d492010-08-25 17:46:15 -07002145 if (lowerPageBound <= i && i <= upperPageBound) {
2146 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002147 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002148 mDirtyPageContent.set(i, false);
2149 }
Winson Chung86f77532010-08-24 11:08:22 -07002150 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002151 }
2152 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002153 }
2154 }
2155
Winson Chunge3193b92010-09-10 11:44:42 -07002156 protected int getAssociatedLowerPageBound(int page) {
2157 return Math.max(0, page - 1);
2158 }
2159 protected int getAssociatedUpperPageBound(int page) {
2160 final int count = getChildCount();
2161 return Math.min(page + 1, count - 1);
2162 }
2163
Winson Chung86f77532010-08-24 11:08:22 -07002164 /**
2165 * This method is called ONLY to synchronize the number of pages that the paged view has.
2166 * To actually fill the pages with information, implement syncPageItems() below. It is
2167 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2168 * and therefore, individual page items do not need to be updated in this method.
2169 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002170 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002171
2172 /**
2173 * This method is called to synchronize the items that are on a particular page. If views on
2174 * the page can be reused, then they should be updated within this method.
2175 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002176 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002177
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002178 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002179 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002180 }
2181 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002182 invalidatePageData(currentPage, false);
2183 }
2184 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002185 if (!mIsDataReady) {
2186 return;
2187 }
2188
Michael Jurka0142d492010-08-25 17:46:15 -07002189 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002190 // Force all scrolling-related behavior to end
2191 mScroller.forceFinished(true);
2192 mNextPage = INVALID_PAGE;
2193
Michael Jurka0142d492010-08-25 17:46:15 -07002194 // Update all the pages
2195 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002196
Winson Chung5a808352011-06-27 19:08:49 -07002197 // We must force a measure after we've loaded the pages to update the content width and
2198 // to determine the full scroll width
2199 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2200 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2201
2202 // Set a new page as the current page if necessary
2203 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002204 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002205 }
2206
Michael Jurka0142d492010-08-25 17:46:15 -07002207 // Mark each of the pages as dirty
2208 final int count = getChildCount();
2209 mDirtyPageContent.clear();
2210 for (int i = 0; i < count; ++i) {
2211 mDirtyPageContent.add(true);
2212 }
2213
2214 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002215 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002216 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002217 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002218 }
Winson Chung007c6982011-06-14 13:27:53 -07002219
Adam Cohen7d30a372013-07-01 17:03:59 -07002220 // Animate the drag view back to the original position
2221 void animateDragViewToOriginalPosition() {
2222 if (mDragView != null) {
2223 AnimatorSet anim = new AnimatorSet();
2224 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2225 anim.playTogether(
2226 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2227 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2228 anim.addListener(new AnimatorListenerAdapter() {
2229 @Override
2230 public void onAnimationEnd(Animator animation) {
2231 onPostReorderingAnimationCompleted();
2232 }
2233 });
2234 anim.start();
2235 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002236 }
2237
Adam Cohen7d30a372013-07-01 17:03:59 -07002238 // "Zooms out" the PagedView to reveal more side pages
2239 protected boolean zoomOut() {
2240 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2241 mZoomInOutAnim.cancel();
2242 }
2243
2244 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2245 mZoomInOutAnim = new AnimatorSet();
2246 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2247 mZoomInOutAnim.playTogether(
2248 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2249 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2250 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2251 @Override
2252 public void onAnimationStart(Animator animation) {
2253 // Show the delete drop target
2254 if (mDeleteDropTarget != null) {
2255 mDeleteDropTarget.setVisibility(View.VISIBLE);
2256 mDeleteDropTarget.animate().alpha(1f)
2257 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2258 .setListener(new AnimatorListenerAdapter() {
2259 @Override
2260 public void onAnimationStart(Animator animation) {
2261 mDeleteDropTarget.setAlpha(0f);
2262 }
2263 });
2264 }
2265 }
2266 });
2267 mZoomInOutAnim.start();
2268 return true;
2269 }
2270 return false;
2271 }
2272
2273 protected void onStartReordering() {
2274 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2275 mTouchState = TOUCH_STATE_REORDERING;
2276 mIsReordering = true;
2277
2278 // Mark all the non-widget pages as invisible
2279 getVisiblePages(mTempVisiblePagesRange);
2280 boundByReorderablePages(true, mTempVisiblePagesRange);
2281 for (int i = 0; i < getPageCount(); ++i) {
2282 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2283 getPageAt(i).setAlpha(0f);
2284 }
2285 }
2286
2287 // We must invalidate to trigger a redraw to update the layers such that the drag view
2288 // is always drawn on top
2289 invalidate();
2290 }
2291
2292 private void onPostReorderingAnimationCompleted() {
2293 // Trigger the callback when reordering has settled
2294 --mPostReorderingPreZoomInRemainingAnimationCount;
2295 if (mPostReorderingPreZoomInRunnable != null &&
2296 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2297 mPostReorderingPreZoomInRunnable.run();
2298 mPostReorderingPreZoomInRunnable = null;
2299 }
2300 }
2301
2302 protected void onEndReordering() {
2303 mIsReordering = false;
2304
2305 // Mark all the non-widget pages as visible again
2306 getVisiblePages(mTempVisiblePagesRange);
2307 boundByReorderablePages(true, mTempVisiblePagesRange);
2308 for (int i = 0; i < getPageCount(); ++i) {
2309 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2310 getPageAt(i).setAlpha(1f);
2311 }
2312 }
2313 }
2314
2315 public boolean startReordering() {
2316 int dragViewIndex = getPageNearestToCenterOfScreen();
2317 mTempVisiblePagesRange[0] = 0;
2318 mTempVisiblePagesRange[1] = getPageCount() - 1;
2319 boundByReorderablePages(true, mTempVisiblePagesRange);
2320 mReorderingStarted = true;
2321
2322 // Check if we are within the reordering range
2323 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2324 dragViewIndex <= mTempVisiblePagesRange[1]) {
2325 if (zoomOut()) {
2326 // Find the drag view under the pointer
2327 mDragView = getChildAt(dragViewIndex);
2328
2329 onStartReordering();
2330 }
2331 return true;
2332 }
2333 return false;
2334 }
2335
2336 boolean isReordering(boolean testTouchState) {
2337 boolean state = mIsReordering;
2338 if (testTouchState) {
2339 state &= (mTouchState == TOUCH_STATE_REORDERING);
2340 }
2341 return state;
2342 }
2343 void endReordering() {
2344 // For simplicity, we call endReordering sometimes even if reordering was never started.
2345 // In that case, we don't want to do anything.
2346 if (!mReorderingStarted) return;
2347 mReorderingStarted = false;
2348
2349 // If we haven't flung-to-delete the current child, then we just animate the drag view
2350 // back into position
2351 final Runnable onCompleteRunnable = new Runnable() {
2352 @Override
2353 public void run() {
2354 onEndReordering();
2355 }
2356 };
2357 if (!mDeferringForDelete) {
2358 mPostReorderingPreZoomInRunnable = new Runnable() {
2359 public void run() {
2360 zoomIn(onCompleteRunnable);
2361 };
2362 };
2363
2364 mPostReorderingPreZoomInRemainingAnimationCount =
2365 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2366 // Snap to the current page
2367 snapToPage(indexOfChild(mDragView), 0);
2368 // Animate the drag view back to the front position
2369 animateDragViewToOriginalPosition();
2370 } else {
2371 // Handled in post-delete-animation-callbacks
2372 }
2373 }
2374
2375 // "Zooms in" the PagedView to highlight the current page
2376 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2377 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2378 mZoomInOutAnim.cancel();
2379 }
2380 if (getScaleX() < 1f || getScaleY() < 1f) {
2381 mZoomInOutAnim = new AnimatorSet();
2382 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2383 mZoomInOutAnim.playTogether(
2384 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2385 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2386 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2387 @Override
2388 public void onAnimationStart(Animator animation) {
2389 // Hide the delete drop target
2390 if (mDeleteDropTarget != null) {
2391 mDeleteDropTarget.animate().alpha(0f)
2392 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2393 .setListener(new AnimatorListenerAdapter() {
2394 @Override
2395 public void onAnimationEnd(Animator animation) {
2396 mDeleteDropTarget.setVisibility(View.GONE);
2397 }
2398 });
2399 }
2400 }
2401 @Override
2402 public void onAnimationCancel(Animator animation) {
2403 mDragView = null;
2404 }
2405 @Override
2406 public void onAnimationEnd(Animator animation) {
2407 mDragView = null;
2408 if (onCompleteRunnable != null) {
2409 onCompleteRunnable.run();
2410 }
2411 }
2412 });
2413 mZoomInOutAnim.start();
2414 return true;
2415 } else {
2416 if (onCompleteRunnable != null) {
2417 onCompleteRunnable.run();
2418 }
2419 }
2420 return false;
2421 }
2422
2423 /*
2424 * Flinging to delete - IN PROGRESS
2425 */
2426 private PointF isFlingingToDelete() {
2427 ViewConfiguration config = ViewConfiguration.get(getContext());
2428 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2429
2430 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2431 // Do a quick dot product test to ensure that we are flinging upwards
2432 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2433 mVelocityTracker.getYVelocity());
2434 PointF upVec = new PointF(0f, -1f);
2435 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2436 (vel.length() * upVec.length()));
2437 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2438 return vel;
2439 }
2440 }
2441 return null;
2442 }
2443
2444 /**
2445 * Creates an animation from the current drag view along its current velocity vector.
2446 * For this animation, the alpha runs for a fixed duration and we update the position
2447 * progressively.
2448 */
2449 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2450 private View mDragView;
2451 private PointF mVelocity;
2452 private Rect mFrom;
2453 private long mPrevTime;
2454 private float mFriction;
2455
2456 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2457
2458 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2459 long startTime, float friction) {
2460 mDragView = dragView;
2461 mVelocity = vel;
2462 mFrom = from;
2463 mPrevTime = startTime;
2464 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2465 }
2466
2467 @Override
2468 public void onAnimationUpdate(ValueAnimator animation) {
2469 float t = ((Float) animation.getAnimatedValue()).floatValue();
2470 long curTime = AnimationUtils.currentAnimationTimeMillis();
2471
2472 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2473 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2474
2475 mDragView.setTranslationX(mFrom.left);
2476 mDragView.setTranslationY(mFrom.top);
2477 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2478
2479 mVelocity.x *= mFriction;
2480 mVelocity.y *= mFriction;
2481 mPrevTime = curTime;
2482 }
2483 };
2484
2485 private static final int ANIM_TAG_KEY = 100;
2486
2487 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2488 return new Runnable() {
2489 @Override
2490 public void run() {
2491 int dragViewIndex = indexOfChild(dragView);
2492
2493 // For each of the pages around the drag view, animate them from the previous
2494 // position to the new position in the layout (as a result of the drag view moving
2495 // in the layout)
2496 // NOTE: We can make an assumption here because we have side-bound pages that we
2497 // will always have pages to animate in from the left
2498 getVisiblePages(mTempVisiblePagesRange);
2499 boundByReorderablePages(true, mTempVisiblePagesRange);
2500 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2501 boolean slideFromLeft = (isLastWidgetPage ||
2502 dragViewIndex > mTempVisiblePagesRange[0]);
2503
2504 // Setup the scroll to the correct page before we swap the views
2505 if (slideFromLeft) {
2506 snapToPageImmediately(dragViewIndex - 1);
2507 }
2508
2509 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2510 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2511 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2512 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2513 ArrayList<Animator> animations = new ArrayList<Animator>();
2514 for (int i = lowerIndex; i <= upperIndex; ++i) {
2515 View v = getChildAt(i);
2516 // dragViewIndex < pageUnderPointIndex, so after we remove the
2517 // drag view all subsequent views to pageUnderPointIndex will
2518 // shift down.
2519 int oldX = 0;
2520 int newX = 0;
2521 if (slideFromLeft) {
2522 if (i == 0) {
2523 // Simulate the page being offscreen with the page spacing
2524 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2525 - mPageSpacing;
2526 } else {
2527 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2528 }
2529 newX = getViewportOffsetX() + getChildOffset(i);
2530 } else {
2531 oldX = getChildOffset(i) - getChildOffset(i - 1);
2532 newX = 0;
2533 }
2534
2535 // Animate the view translation from its old position to its new
2536 // position
2537 AnimatorSet anim = (AnimatorSet) v.getTag();
2538 if (anim != null) {
2539 anim.cancel();
2540 }
2541
2542 // Note: Hacky, but we want to skip any optimizations to not draw completely
2543 // hidden views
2544 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2545 v.setTranslationX(oldX - newX);
2546 anim = new AnimatorSet();
2547 anim.playTogether(
2548 ObjectAnimator.ofFloat(v, "translationX", 0f),
2549 ObjectAnimator.ofFloat(v, "alpha", 1f));
2550 animations.add(anim);
2551 v.setTag(ANIM_TAG_KEY, anim);
2552 }
2553
2554 AnimatorSet slideAnimations = new AnimatorSet();
2555 slideAnimations.playTogether(animations);
2556 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2557 slideAnimations.addListener(new AnimatorListenerAdapter() {
2558 @Override
2559 public void onAnimationEnd(Animator animation) {
2560 final Runnable onCompleteRunnable = new Runnable() {
2561 @Override
2562 public void run() {
2563 mDeferringForDelete = false;
2564 onEndReordering();
2565 onRemoveViewAnimationCompleted();
2566 }
2567 };
2568 zoomIn(onCompleteRunnable);
2569 }
2570 });
2571 slideAnimations.start();
2572
2573 removeView(dragView);
2574 onRemoveView(dragView, true);
2575 }
2576 };
2577 }
2578
2579 public void onFlingToDelete(PointF vel) {
2580 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2581
2582 // NOTE: Because it takes time for the first frame of animation to actually be
2583 // called and we expect the animation to be a continuation of the fling, we have
2584 // to account for the time that has elapsed since the fling finished. And since
2585 // we don't have a startDelay, we will always get call to update when we call
2586 // start() (which we want to ignore).
2587 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2588 private int mCount = -1;
2589 private long mStartTime;
2590 private float mOffset;
2591 /* Anonymous inner class ctor */ {
2592 mStartTime = startTime;
2593 }
2594
2595 @Override
2596 public float getInterpolation(float t) {
2597 if (mCount < 0) {
2598 mCount++;
2599 } else if (mCount == 0) {
2600 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2601 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2602 mCount++;
2603 }
2604 return Math.min(1f, mOffset + t);
2605 }
2606 };
2607
2608 final Rect from = new Rect();
2609 final View dragView = mDragView;
2610 from.left = (int) dragView.getTranslationX();
2611 from.top = (int) dragView.getTranslationY();
2612 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2613 from, startTime, FLING_TO_DELETE_FRICTION);
2614
2615 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2616
2617 // Create and start the animation
2618 ValueAnimator mDropAnim = new ValueAnimator();
2619 mDropAnim.setInterpolator(tInterpolator);
2620 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2621 mDropAnim.setFloatValues(0f, 1f);
2622 mDropAnim.addUpdateListener(updateCb);
2623 mDropAnim.addListener(new AnimatorListenerAdapter() {
2624 public void onAnimationEnd(Animator animation) {
2625 onAnimationEndRunnable.run();
2626 }
2627 });
2628 mDropAnim.start();
2629 mDeferringForDelete = true;
2630 }
2631
2632 /* Drag to delete */
2633 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2634 if (mDeleteDropTarget != null) {
2635 mAltTmpRect.set(0, 0, 0, 0);
2636 View parent = (View) mDeleteDropTarget.getParent();
2637 if (parent != null) {
2638 parent.getGlobalVisibleRect(mAltTmpRect);
2639 }
2640 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2641 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2642 return mTmpRect.contains(x, y);
2643 }
2644 return false;
2645 }
2646
2647 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2648
2649 private void onDropToDelete() {
2650 final View dragView = mDragView;
2651
2652 final float toScale = 0f;
2653 final float toAlpha = 0f;
2654
2655 // Create and start the complex animation
2656 ArrayList<Animator> animations = new ArrayList<Animator>();
2657 AnimatorSet motionAnim = new AnimatorSet();
2658 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2659 motionAnim.playTogether(
2660 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2661 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2662 animations.add(motionAnim);
2663
2664 AnimatorSet alphaAnim = new AnimatorSet();
2665 alphaAnim.setInterpolator(new LinearInterpolator());
2666 alphaAnim.playTogether(
2667 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2668 animations.add(alphaAnim);
2669
2670 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2671
2672 AnimatorSet anim = new AnimatorSet();
2673 anim.playTogether(animations);
2674 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2675 anim.addListener(new AnimatorListenerAdapter() {
2676 public void onAnimationEnd(Animator animation) {
2677 onAnimationEndRunnable.run();
2678 }
2679 });
2680 anim.start();
2681
2682 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002683 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002684
2685 /* Accessibility */
2686 @Override
2687 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2688 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002689 info.setScrollable(getPageCount() > 1);
2690 if (getCurrentPage() < getPageCount() - 1) {
2691 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2692 }
2693 if (getCurrentPage() > 0) {
2694 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2695 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002696 }
2697
2698 @Override
2699 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2700 super.onInitializeAccessibilityEvent(event);
2701 event.setScrollable(true);
2702 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2703 event.setFromIndex(mCurrentPage);
2704 event.setToIndex(mCurrentPage);
2705 event.setItemCount(getChildCount());
2706 }
2707 }
2708
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002709 @Override
2710 public boolean performAccessibilityAction(int action, Bundle arguments) {
2711 if (super.performAccessibilityAction(action, arguments)) {
2712 return true;
2713 }
2714 switch (action) {
2715 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2716 if (getCurrentPage() < getPageCount() - 1) {
2717 scrollRight();
2718 return true;
2719 }
2720 } break;
2721 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2722 if (getCurrentPage() > 0) {
2723 scrollLeft();
2724 return true;
2725 }
2726 } break;
2727 }
2728 return false;
2729 }
2730
Adam Cohen0ffac432013-07-10 11:19:26 -07002731 protected String getCurrentPageDescription() {
2732 return String.format(getContext().getString(R.string.default_scroll_format),
2733 getNextPage() + 1, getChildCount());
2734 }
2735
Winson Chungd11265e2011-08-30 13:37:23 -07002736 @Override
2737 public boolean onHoverEvent(android.view.MotionEvent event) {
2738 return true;
2739 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002740}