blob: 0b0c4b988d6cc06d9708010156a887ad12e344cd [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen9c4949e2010-10-05 12:27:22 -070027import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070028import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070029import android.graphics.Matrix;
30import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070031import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070032import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070033import android.os.Parcel;
34import android.os.Parcelable;
35import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070036import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070037import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080038import android.view.InputDevice;
39import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070040import android.view.MotionEvent;
41import android.view.VelocityTracker;
42import android.view.View;
43import android.view.ViewConfiguration;
44import android.view.ViewGroup;
45import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070046import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070047import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070049import android.view.animation.AnimationUtils;
50import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080051import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070052import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070053import android.widget.Scroller;
54
Winson Chung6a0f57d2011-06-29 20:10:49 -070055import java.util.ArrayList;
56
Winson Chungc58497e2013-09-03 17:48:37 -070057interface Page {
58 public int getPageChildCount();
59 public View getChildOnPageAt(int i);
60 public void removeAllViewsOnPage();
61 public void removeViewOnPageAt(int i);
62 public int indexOfChildOnPage(View v);
63}
64
Winson Chung321e9ee2010-08-09 13:37:56 -070065/**
66 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070067 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070068 */
Michael Jurka8b805b12012-04-18 14:23:14 -070069public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070070 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070071 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070072 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070073
Winson Chung86f77532010-08-24 11:08:22 -070074 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070075 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070076
Adam Cohen7d30a372013-07-01 17:03:59 -070077 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070078 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070079 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070080
Adam Cohenb5ba0972011-09-07 18:02:31 -070081 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070082 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080083
Adam Cohenb64cb5a2011-02-15 13:53:42 -080084 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080085 // The page is moved more than halfway, automatically move to the next page on touch up.
86 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080087
Adam Cohen265b9a62011-12-07 14:37:18 -080088 // The following constants need to be scaled based on density. The scaled versions will be
89 // assigned to the corresponding member variables below.
90 private static final int FLING_THRESHOLD_VELOCITY = 500;
91 private static final int MIN_SNAP_VELOCITY = 1500;
92 private static final int MIN_FLING_VELOCITY = 250;
93
Adam Cohen7d30a372013-07-01 17:03:59 -070094 // We are disabling touch interaction of the widget region for factory ROM.
95 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070096 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070097 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070098
Adam Cohenf358a4b2013-07-23 16:47:31 -070099 private boolean mFreeScroll = false;
100 private int mFreeScrollMinScrollX = -1;
101 private int mFreeScrollMaxScrollX = -1;
102
Winson Chung8aad6102012-05-11 16:27:49 -0700103 static final int AUTOMATIC_PAGE_SPACING = -1;
104
Adam Cohen265b9a62011-12-07 14:37:18 -0800105 protected int mFlingThresholdVelocity;
106 protected int mMinFlingVelocity;
107 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700108
Adam Cohenb5ba0972011-09-07 18:02:31 -0700109 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700110 protected float mSmoothingTime;
111 protected float mTouchX;
112
113 protected boolean mFirstLayout = true;
114
115 protected int mCurrentPage;
Winson Chung8c87cd82013-07-23 16:20:10 -0700116 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700117 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700118
Michael Jurka0142d492010-08-25 17:46:15 -0700119 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800120 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700121 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700122 private VelocityTracker mVelocityTracker;
123
Adam Cohen7d30a372013-07-01 17:03:59 -0700124 private float mParentDownMotionX;
125 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700126 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700127 private float mDownMotionY;
128 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700129 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800130 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800131 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800132 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800133 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700134 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700135
136 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700137
Michael Jurka0142d492010-08-25 17:46:15 -0700138 protected final static int TOUCH_STATE_REST = 0;
139 protected final static int TOUCH_STATE_SCROLLING = 1;
140 protected final static int TOUCH_STATE_PREV_PAGE = 2;
141 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700142 protected final static int TOUCH_STATE_REORDERING = 4;
143
Adam Cohene45440e2010-10-14 18:33:38 -0700144 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700145
Michael Jurka0142d492010-08-25 17:46:15 -0700146 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700147 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700148
Michael Jurka0142d492010-08-25 17:46:15 -0700149 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700150
Michael Jurka7426c422010-11-11 15:23:47 -0800151 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700152 private int mPagingTouchSlop;
153 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700154 protected int mPageSpacing;
155 protected int mPageLayoutPaddingTop;
156 protected int mPageLayoutPaddingBottom;
157 protected int mPageLayoutPaddingLeft;
158 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700159 protected int mPageLayoutWidthGap;
160 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700161 protected int mCellCountX = 0;
162 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700163 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800164 protected boolean mAllowOverScroll = true;
165 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800166 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700167 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700168
Michael Jurka8b805b12012-04-18 14:23:14 -0700169 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800170 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
171 // the screens from continuing to translate beyond the normal bounds.
172 protected int mOverScrollX;
173
Michael Jurka5f1c5092010-09-03 14:15:02 -0700174 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700175
Michael Jurka5f1c5092010-09-03 14:15:02 -0700176 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700177
Winson Chung86f77532010-08-24 11:08:22 -0700178 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700179
Michael Jurkae326f182011-11-21 14:05:46 -0800180 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700181
Michael Jurka0142d492010-08-25 17:46:15 -0700182 // If true, syncPages and syncPageItems will be called to refresh pages
183 protected boolean mContentIsRefreshable = true;
184
185 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700186 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700187
188 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
189 // to switch to a new page
190 protected boolean mUsePagingTouchSlop = true;
191
Michael Jurka8b805b12012-04-18 14:23:14 -0700192 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700193 // (SmoothPagedView does this)
194 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700195 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700196
Patrick Dubroy1262e362010-10-06 15:49:50 -0700197 protected boolean mIsPageMoving = false;
198
Winson Chungf0ea4d32011-06-06 14:27:16 -0700199 // All syncs and layout passes are deferred until data is ready.
200 protected boolean mIsDataReady = false;
201
Adam Cohen7d30a372013-07-01 17:03:59 -0700202 protected boolean mAllowLongPress = true;
203
Winson Chungd2be3812013-07-16 11:11:32 -0700204 // Page Indicator
205 private int mPageIndicatorViewId;
206 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700207 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700208
Adam Cohen7d30a372013-07-01 17:03:59 -0700209 // The viewport whether the pages are to be contained (the actual view may be larger than the
210 // viewport)
211 private Rect mViewport = new Rect();
212
213 // Reordering
214 // We use the min scale to determine how much to expand the actually PagedView measured
215 // dimensions such that when we are zoomed out, the view is not clipped
216 private int REORDERING_DROP_REPOSITION_DURATION = 200;
217 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
218 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700219 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700220 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700221 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700222 protected View mDragView;
223 protected AnimatorSet mZoomInOutAnim;
224 private Runnable mSidePageHoverRunnable;
225 private int mSidePageHoverIndex = -1;
226 // This variable's scope is only for the duration of startReordering() and endReordering()
227 private boolean mReorderingStarted = false;
228 // This variable's scope is for the duration of startReordering() and after the zoomIn()
229 // animation after endReordering()
230 private boolean mIsReordering;
231 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
232 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
233 private int mPostReorderingPreZoomInRemainingAnimationCount;
234 private Runnable mPostReorderingPreZoomInRunnable;
235
Adam Cohen7d30a372013-07-01 17:03:59 -0700236 // Convenience/caching
237 private Matrix mTmpInvMatrix = new Matrix();
238 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700239 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700240 private Rect mTmpRect = new Rect();
241 private Rect mAltTmpRect = new Rect();
242
243 // Fling to delete
244 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
245 private float FLING_TO_DELETE_FRICTION = 0.035f;
246 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
247 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
248 protected int mFlingToDeleteThresholdVelocity = -1400;
249 // Drag to delete
250 private boolean mDeferringForDelete = false;
251 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
252 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
253
254 // Drop to delete
255 private View mDeleteDropTarget;
256
257 private boolean mAutoComputePageSpacing = false;
258 private boolean mRecomputePageSpacing = false;
259
260 // Bouncer
261 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700262
John Spurlock77e1f472013-09-11 10:09:51 -0400263 protected final Rect mInsets = new Rect();
264
Winson Chung86f77532010-08-24 11:08:22 -0700265 public interface PageSwitchListener {
266 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700267 }
268
Winson Chung321e9ee2010-08-09 13:37:56 -0700269 public PagedView(Context context) {
270 this(context, null);
271 }
272
273 public PagedView(Context context, AttributeSet attrs) {
274 this(context, attrs, 0);
275 }
276
277 public PagedView(Context context, AttributeSet attrs, int defStyle) {
278 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700279
Adam Cohen9c4949e2010-10-05 12:27:22 -0700280 TypedArray a = context.obtainStyledAttributes(attrs,
281 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800282 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700283 if (mPageSpacing < 0) {
284 mAutoComputePageSpacing = mRecomputePageSpacing = true;
285 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700286 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800287 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700288 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800289 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700290 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800291 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700292 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800293 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700294 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700295 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700296 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700297 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700298 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700299 a.recycle();
300
Winson Chung321e9ee2010-08-09 13:37:56 -0700301 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700302 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700303 }
304
305 /**
306 * Initializes various states for this workspace.
307 */
Michael Jurka0142d492010-08-25 17:46:15 -0700308 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700309 mDirtyPageContent = new ArrayList<Boolean>();
310 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800311 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700312 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700313 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700314
315 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700316 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700317 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
318 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700319 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800320
Adam Cohen7d30a372013-07-01 17:03:59 -0700321 // Scale the fling-to-delete threshold by the density
322 mFlingToDeleteThresholdVelocity =
323 (int) (mFlingToDeleteThresholdVelocity * mDensity);
324
Adam Cohen265b9a62011-12-07 14:37:18 -0800325 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
326 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
327 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700328 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700329 }
330
Winson Chungd2be3812013-07-16 11:11:32 -0700331 protected void onAttachedToWindow() {
332 // Hook up the page indicator
333 ViewGroup parent = (ViewGroup) getParent();
334 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
335 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700336 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700337
338 ArrayList<Integer> markers = new ArrayList<Integer>();
339 for (int i = 0; i < getChildCount(); ++i) {
340 markers.add(getPageIndicatorMarker(i));
341 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700342
Winson Chungc58497e2013-09-03 17:48:37 -0700343 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Adam Cohenf358a4b2013-07-23 16:47:31 -0700344 mPageIndicator.setOnClickListener((Launcher) getContext());
Winson Chungd2be3812013-07-16 11:11:32 -0700345 }
346 }
347
348 protected void onDetachedFromWindow() {
349 // Unhook the page indicator
350 mPageIndicator = null;
351 }
352
Adam Cohen7d30a372013-07-01 17:03:59 -0700353 void setDeleteDropTarget(View v) {
354 mDeleteDropTarget = v;
355 }
356
357 // Convenience methods to map points from self to parent and vice versa
358 float[] mapPointFromViewToParent(View v, float x, float y) {
359 mTmpPoint[0] = x;
360 mTmpPoint[1] = y;
361 v.getMatrix().mapPoints(mTmpPoint);
362 mTmpPoint[0] += v.getLeft();
363 mTmpPoint[1] += v.getTop();
364 return mTmpPoint;
365 }
366 float[] mapPointFromParentToView(View v, float x, float y) {
367 mTmpPoint[0] = x - v.getLeft();
368 mTmpPoint[1] = y - v.getTop();
369 v.getMatrix().invert(mTmpInvMatrix);
370 mTmpInvMatrix.mapPoints(mTmpPoint);
371 return mTmpPoint;
372 }
373
374 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700375 if (mDragView != null) {
376 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
377 (mDragViewBaselineLeft - mDragView.getLeft());
378 float y = mLastMotionY - mDownMotionY;
379 mDragView.setTranslationX(x);
380 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700381
Adam Cohenf358a4b2013-07-23 16:47:31 -0700382 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
383 + x + ", " + y);
384 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700385 }
386
387 public void setMinScale(float f) {
388 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700389 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700390 requestLayout();
391 }
392
393 @Override
394 public void setScaleX(float scaleX) {
395 super.setScaleX(scaleX);
396 if (isReordering(true)) {
397 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
398 mLastMotionX = p[0];
399 mLastMotionY = p[1];
400 updateDragViewTranslationDuringDrag();
401 }
402 }
403
404 // Convenience methods to get the actual width/height of the PagedView (since it is measured
405 // to be larger to account for the minimum possible scale)
406 int getViewportWidth() {
407 return mViewport.width();
408 }
409 int getViewportHeight() {
410 return mViewport.height();
411 }
412
413 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
414 // PagedView both horizontally and vertically
415 int getViewportOffsetX() {
416 return (getMeasuredWidth() - getViewportWidth()) / 2;
417 }
418
419 int getViewportOffsetY() {
420 return (getMeasuredHeight() - getViewportHeight()) / 2;
421 }
422
Adam Cohenedb40762013-07-18 16:45:45 -0700423 PageIndicator getPageIndicator() {
424 return mPageIndicator;
425 }
Winson Chung82dfe582013-07-26 15:07:49 -0700426 protected int getPageIndicatorMarker(int pageIndex) {
427 return R.layout.page_indicator_marker;
428 }
Adam Cohenedb40762013-07-18 16:45:45 -0700429
Winson Chung86f77532010-08-24 11:08:22 -0700430 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
431 mPageSwitchListener = pageSwitchListener;
432 if (mPageSwitchListener != null) {
433 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700434 }
435 }
436
437 /**
Winson Chung52aee602013-01-30 12:01:02 -0800438 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
439 */
440 public boolean isLayoutRtl() {
441 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
442 }
443
444 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700445 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
446 * out pages.
447 */
448 protected void setDataIsReady() {
449 mIsDataReady = true;
450 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700451
Winson Chungf0ea4d32011-06-06 14:27:16 -0700452 protected boolean isDataReady() {
453 return mIsDataReady;
454 }
455
456 /**
Winson Chung86f77532010-08-24 11:08:22 -0700457 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700458 *
Winson Chung86f77532010-08-24 11:08:22 -0700459 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700460 */
Winson Chung86f77532010-08-24 11:08:22 -0700461 int getCurrentPage() {
462 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700463 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700464
Winson Chung360e63f2012-04-27 13:48:05 -0700465 int getNextPage() {
466 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
467 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700468
Winson Chung86f77532010-08-24 11:08:22 -0700469 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700470 return getChildCount();
471 }
472
Winson Chung86f77532010-08-24 11:08:22 -0700473 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700474 return getChildAt(index);
475 }
476
Adam Cohenae4f1552011-10-20 00:15:42 -0700477 protected int indexToPage(int index) {
478 return index;
479 }
480
Winson Chung321e9ee2010-08-09 13:37:56 -0700481 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800482 * Updates the scroll of the current page immediately to its final scroll position. We use this
483 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
484 * the previous tab page.
485 */
486 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700487 // If the current page is invalid, just reset the scroll position to zero
488 int newX = 0;
489 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700490 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700491 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800492 scrollTo(newX, 0);
493 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800494 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800495 }
496
497 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700498 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
499 * ends, {@link #resumeScrolling()} should be called, along with
500 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
501 */
502 void pauseScrolling() {
503 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700504 }
505
506 /**
507 * Enables scrolling again.
508 * @see #pauseScrolling()
509 */
510 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700511 }
512 /**
Winson Chung86f77532010-08-24 11:08:22 -0700513 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700514 */
Winson Chung86f77532010-08-24 11:08:22 -0700515 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800516 if (!mScroller.isFinished()) {
517 mScroller.abortAnimation();
518 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800519 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
520 // the default
521 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800522 return;
523 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700524
Adam Cohene61a9a22013-06-11 15:45:31 -0700525 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700526 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700527 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700528 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800529 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700530 }
531
Winson Chung8c87cd82013-07-23 16:20:10 -0700532 /**
533 * The restore page will be set in place of the current page at the next (likely first)
534 * layout.
535 */
536 void setRestorePage(int restorePage) {
537 mRestorePage = restorePage;
538 }
539
Michael Jurka0142d492010-08-25 17:46:15 -0700540 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700541 if (mPageSwitchListener != null) {
542 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700543 }
Winson Chungd2be3812013-07-16 11:11:32 -0700544
545 // Update the page indicator (when we aren't reordering)
546 if (mPageIndicator != null && !isReordering(false)) {
547 mPageIndicator.setActiveMarker(getNextPage());
548 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700549 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800550 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700551 if (!mIsPageMoving) {
552 mIsPageMoving = true;
553 onPageBeginMoving();
554 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700555 }
556
Michael Jurkace7e05f2011-02-01 22:02:35 -0800557 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700558 if (mIsPageMoving) {
559 mIsPageMoving = false;
560 onPageEndMoving();
561 }
Michael Jurka0142d492010-08-25 17:46:15 -0700562 }
563
Adam Cohen26976d92011-03-22 15:33:33 -0700564 protected boolean isPageMoving() {
565 return mIsPageMoving;
566 }
567
Michael Jurka0142d492010-08-25 17:46:15 -0700568 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700569 protected void onPageBeginMoving() {
570 }
571
572 // a method that subclasses can override to add behavior
573 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700574 }
575
Winson Chung321e9ee2010-08-09 13:37:56 -0700576 /**
Winson Chung86f77532010-08-24 11:08:22 -0700577 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700578 *
579 * @param l The listener used to respond to long clicks.
580 */
581 @Override
582 public void setOnLongClickListener(OnLongClickListener l) {
583 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700584 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700585 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700586 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700587 }
588 }
589
590 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800591 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700592 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800593 }
594
595 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700596 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700597 // In free scroll mode, we clamp the scrollX
598 if (mFreeScroll) {
599 x = Math.min(x, mFreeScrollMaxScrollX);
600 x = Math.max(x, mFreeScrollMinScrollX);
601 }
602
Adam Cohen0ffac432013-07-10 11:19:26 -0700603 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800604 mUnboundedScrollX = x;
605
Adam Cohen0ffac432013-07-10 11:19:26 -0700606 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
607 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
608 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800609 super.scrollTo(0, y);
610 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700611 if (isRtl) {
612 overScroll(x - mMaxScrollX);
613 } else {
614 overScroll(x);
615 }
Adam Cohen68d73932010-11-15 10:50:58 -0800616 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700617 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800618 super.scrollTo(mMaxScrollX, y);
619 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700620 if (isRtl) {
621 overScroll(x);
622 } else {
623 overScroll(x - mMaxScrollX);
624 }
Adam Cohen68d73932010-11-15 10:50:58 -0800625 }
626 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800627 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800628 super.scrollTo(x, y);
629 }
630
Michael Jurka0142d492010-08-25 17:46:15 -0700631 mTouchX = x;
632 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700633
634 // Update the last motion events when scrolling
635 if (isReordering(true)) {
636 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
637 mLastMotionX = p[0];
638 mLastMotionY = p[1];
639 updateDragViewTranslationDuringDrag();
640 }
Michael Jurka0142d492010-08-25 17:46:15 -0700641 }
642
643 // we moved this functionality to a helper function so SmoothPagedView can reuse it
644 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700645 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700646 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700647 if (getScrollX() != mScroller.getCurrX()
648 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700649 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700650 float scaleX = mFreeScroll ? getScaleX() : 1f;
651 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
652 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700653 }
Michael Jurka0142d492010-08-25 17:46:15 -0700654 invalidate();
655 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700656 } else if (mNextPage != INVALID_PAGE) {
657 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700658 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700659 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700660
Winson Chung9c0565f2013-07-19 13:49:06 -0700661 // Load the associated pages if necessary
662 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
663 loadAssociatedPages(mCurrentPage);
664 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
665 }
666
Adam Cohen73aa9752010-11-24 16:26:58 -0800667 // We don't want to trigger a page end moving unless the page has settled
668 // and the user has stopped scrolling
669 if (mTouchState == TOUCH_STATE_REST) {
670 pageEndMoving();
671 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700672
Adam Cohen7d30a372013-07-01 17:03:59 -0700673 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700674 // Notify the user when the page changes
675 AccessibilityManager accessibilityManager = (AccessibilityManager)
676 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
677 if (accessibilityManager.isEnabled()) {
678 AccessibilityEvent ev =
679 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
680 ev.getText().add(getCurrentPageDescription());
681 sendAccessibilityEventUnchecked(ev);
682 }
Michael Jurka0142d492010-08-25 17:46:15 -0700683 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700684 }
Michael Jurka0142d492010-08-25 17:46:15 -0700685 return false;
686 }
687
688 @Override
689 public void computeScroll() {
690 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700691 }
692
Adam Cohen7d30a372013-07-01 17:03:59 -0700693 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
694 return mTopAlignPageWhenShrinkingForBouncer;
695 }
696
Adam Cohen96d30a12013-07-16 18:13:21 -0700697 public static class LayoutParams extends ViewGroup.LayoutParams {
698 public boolean isFullScreenPage = false;
699
700 /**
701 * {@inheritDoc}
702 */
703 public LayoutParams(int width, int height) {
704 super(width, height);
705 }
706
707 public LayoutParams(ViewGroup.LayoutParams source) {
708 super(source);
709 }
710 }
711
712 protected LayoutParams generateDefaultLayoutParams() {
713 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
714 }
715
Adam Cohenedb40762013-07-18 16:45:45 -0700716 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700717 LayoutParams lp = generateDefaultLayoutParams();
718 lp.isFullScreenPage = true;
719 super.addView(page, 0, lp);
720 }
721
Winson Chung321e9ee2010-08-09 13:37:56 -0700722 @Override
723 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700724 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700725 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
726 return;
727 }
728
Adam Cohen7d30a372013-07-01 17:03:59 -0700729 // We measure the dimensions of the PagedView to be larger than the pages so that when we
730 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700731 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
732 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
733 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700734 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700735 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
736 // viewport, we can be at most one and a half screens offset once we scale down
737 DisplayMetrics dm = getResources().getDisplayMetrics();
738 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
Winson Chungc58497e2013-09-03 17:48:37 -0700739 int parentWidthSize, parentHeightSize;
740 int scaledWidthSize, scaledHeightSize;
741 if (mUseMinScale) {
742 parentWidthSize = (int) (1.5f * maxSize);
743 parentHeightSize = maxSize;
744 scaledWidthSize = (int) (parentWidthSize / mMinScale);
745 scaledHeightSize = (int) (parentHeightSize / mMinScale);
746 } else {
747 scaledWidthSize = widthSize;
748 scaledHeightSize = heightSize;
749 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700750 mViewport.set(0, 0, widthSize, heightSize);
751
752 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
753 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
754 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700755 }
756
Winson Chung8aad6102012-05-11 16:27:49 -0700757 // Return early if we aren't given a proper dimension
758 if (widthSize <= 0 || heightSize <= 0) {
759 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
760 return;
761 }
762
Adam Lesinski6b879f02010-11-04 16:15:23 -0700763 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
764 * of the All apps view on XLarge displays to not take up more space then it needs. Width
765 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
766 * each page to have the same width.
767 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700768 final int verticalPadding = getPaddingTop() + getPaddingBottom();
769 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700770
771 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700772 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700773 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700774 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
775 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
776 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
777 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700778 final int childCount = getChildCount();
779 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700780 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700781 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700782 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
783
784 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700785 int childHeightMode;
786 int childWidth;
787 int childHeight;
788
789 if (!lp.isFullScreenPage) {
790 if (lp.width == LayoutParams.WRAP_CONTENT) {
791 childWidthMode = MeasureSpec.AT_MOST;
792 } else {
793 childWidthMode = MeasureSpec.EXACTLY;
794 }
795
796 if (lp.height == LayoutParams.WRAP_CONTENT) {
797 childHeightMode = MeasureSpec.AT_MOST;
798 } else {
799 childHeightMode = MeasureSpec.EXACTLY;
800 }
801
802 childWidth = widthSize - horizontalPadding;
John Spurlock77e1f472013-09-11 10:09:51 -0400803 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
Adam Cohen96d30a12013-07-16 18:13:21 -0700804
Michael Jurka5f1c5092010-09-03 14:15:02 -0700805 } else {
806 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700807 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700808
Winson Chungc58497e2013-09-03 17:48:37 -0700809 if (mUseMinScale) {
810 childWidth = getViewportWidth();
811 childHeight = getViewportHeight();
812 } else {
813 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
814 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
815 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700816 }
817
818 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700819 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
820 final int childHeightMeasureSpec =
821 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700822 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700823 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700824 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700825
Winson Chunga128a7b2012-04-30 15:23:15 -0700826 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700827 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700828 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700829 // The gap between pages in the PagedView should be equal to the gap from the page
830 // to the edge of the screen (so it is not visible in the current screen). To
831 // account for unequal padding on each side of the paged view, we take the maximum
832 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700833 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700834 int spacing = Math.max(offset, widthSize - offset -
835 getChildAt(0).getMeasuredWidth());
836 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700837 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700838 }
839 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700840 }
841
Adam Cohen60b07122011-11-14 17:26:06 -0800842 public void setPageSpacing(int pageSpacing) {
843 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700844 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800845 }
846
Winson Chung321e9ee2010-08-09 13:37:56 -0700847 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700848 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700849 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700850 return;
851 }
852
Winson Chung785d2eb2011-04-14 16:08:02 -0700853 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700854 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700855
Adam Cohenedb40762013-07-18 16:45:45 -0700856 int screenWidth = getViewportWidth();
857
Adam Cohen7d30a372013-07-01 17:03:59 -0700858 int offsetX = getViewportOffsetX();
859 int offsetY = getViewportOffsetY();
860
861 // Update the viewport offsets
862 mViewport.offset(offsetX, offsetY);
863
Adam Cohen0ffac432013-07-10 11:19:26 -0700864 final boolean isRtl = isLayoutRtl();
865
866 final int startIndex = isRtl ? childCount - 1 : 0;
867 final int endIndex = isRtl ? -1 : childCount;
868 final int delta = isRtl ? -1 : 1;
869
Adam Cohen7d30a372013-07-01 17:03:59 -0700870 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700871 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
872
873 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
874 mPageScrolls = new int[getChildCount()];
875 }
876
Adam Cohen0ffac432013-07-10 11:19:26 -0700877 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700878 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700879 LayoutParams lp = (LayoutParams) child.getLayoutParams();
880 int childTop;
Adam Cohen96d30a12013-07-16 18:13:21 -0700881 if (lp.isFullScreenPage) {
882 childTop = offsetY;
883 } else {
John Spurlock77e1f472013-09-11 10:09:51 -0400884 childTop = offsetY + getPaddingTop() + mInsets.top;
Adam Cohen96d30a12013-07-16 18:13:21 -0700885 if (mCenterPagesVertically) {
John Spurlock77e1f472013-09-11 10:09:51 -0400886 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
Adam Cohen96d30a12013-07-16 18:13:21 -0700887 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700888 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700889
Winson Chung321e9ee2010-08-09 13:37:56 -0700890 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700891 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700892 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800893
Winson Chung785d2eb2011-04-14 16:08:02 -0700894 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700895 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800896 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700897
898 // We assume the left and right padding are equal, and hence center the pages
899 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700900 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700901 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
902
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700903 if (i != endIndex - delta) {
904 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
905 childLeft += childWidth + nextScrollOffset;
906 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700907 }
908 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700909
910 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
911 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800912 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700913 setHorizontalScrollBarEnabled(true);
914 mFirstLayout = false;
915 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700916
917 if (childCount > 0) {
918 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700919 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700920 } else {
921 mMaxScrollX = 0;
922 }
923
924 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
925 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700926 if (mRestorePage > -1) {
927 setCurrentPage(mRestorePage);
928 mRestorePage = -1;
929 } else {
930 setCurrentPage(getNextPage());
931 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700932 }
933 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700934
935 if (isReordering(true)) {
936 updateDragViewTranslationDuringDrag();
937 }
Winson Chunge3193b92010-09-10 11:44:42 -0700938 }
939
Adam Cohenf34bab52010-09-30 14:11:56 -0700940 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700941 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
942
943 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700944 for (int i = 0; i < getChildCount(); i++) {
945 View child = getChildAt(i);
946 if (child != null) {
947 float scrollProgress = getScrollProgress(screenCenter, child, i);
948 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800949 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700950 }
951 }
952 invalidate();
953 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700954 }
955
Winson Chungc58497e2013-09-03 17:48:37 -0700956 protected void enablePagedViewAnimations() {
957 mAllowPagedViewAnimations = true;
958
959 }
960 protected void disablePagedViewAnimations() {
961 mAllowPagedViewAnimations = false;
962 }
963
Winson Chunge3193b92010-09-10 11:44:42 -0700964 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700965 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700966 // Update the page indicator, we don't update the page indicator as we
967 // add/remove pages
968 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700969 int pageIndex = indexOfChild(child);
Winson Chungc58497e2013-09-03 17:48:37 -0700970 mPageIndicator.addMarker(pageIndex, getPageIndicatorMarker(pageIndex),
971 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700972 }
973
Adam Cohen2591f6a2011-10-25 14:36:40 -0700974 // This ensures that when children are added, they get the correct transforms / alphas
975 // in accordance with any scroll effects.
976 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700977 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700978
Adam Cohen2591f6a2011-10-25 14:36:40 -0700979 invalidate();
980 }
981
Michael Jurka8b805b12012-04-18 14:23:14 -0700982 @Override
983 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700984 mForceScreenScrolled = true;
985 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700986 }
987
Winson Chungd2be3812013-07-16 11:11:32 -0700988 private void removeMarkerForView(int index) {
989 // Update the page indicator, we don't update the page indicator as we
990 // add/remove pages
991 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -0700992 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700993 }
994 }
995
996 @Override
997 public void removeView(View v) {
998 // XXX: We should find a better way to hook into this before the view
999 // gets removed form its parent...
1000 removeMarkerForView(indexOfChild(v));
1001 super.removeView(v);
1002 }
1003 @Override
1004 public void removeViewInLayout(View v) {
1005 // XXX: We should find a better way to hook into this before the view
1006 // gets removed form its parent...
1007 removeMarkerForView(indexOfChild(v));
1008 super.removeViewInLayout(v);
1009 }
1010 @Override
1011 public void removeViewAt(int index) {
1012 // XXX: We should find a better way to hook into this before the view
1013 // gets removed form its parent...
1014 removeViewAt(index);
1015 super.removeViewAt(index);
1016 }
1017 @Override
1018 public void removeAllViewsInLayout() {
1019 // Update the page indicator, we don't update the page indicator as we
1020 // add/remove pages
1021 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001022 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001023 }
1024
1025 super.removeAllViewsInLayout();
1026 }
1027
Adam Cohen73894962011-10-31 13:17:17 -07001028 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001029 if (index < 0 || index > getChildCount() - 1) return 0;
1030
Adam Cohen0ffac432013-07-10 11:19:26 -07001031 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -07001032
Adam Cohenf698c6e2013-07-17 18:44:25 -07001033 if (isRtl) index = getChildCount() - index - 1;
1034 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001035
Adam Cohenf698c6e2013-07-17 18:44:25 -07001036 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001037 }
1038
Adam Cohenf358a4b2013-07-23 16:47:31 -07001039 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001040 range[0] = 0;
1041 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001042 }
1043
Michael Jurkadde558b2011-11-09 22:09:06 -08001044 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001045 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001046 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001047
Michael Jurkac4fb9172010-09-02 17:19:20 -07001048 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001049 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -07001050 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -07001051 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001052
Winson Chungc9ca2982013-07-19 12:07:38 -07001053 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
1054 View currPage = getPageAt(leftScreen);
1055
1056 // Check if the right edge of the page is in the viewport
1057 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Winson Chungc763c4e2013-07-19 13:49:06 -07001058 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001059 if (mTmpIntPoint[0] < 0) {
1060 break;
1061 }
1062 }
1063 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1064 View currPage = getPageAt(rightScreen);
1065
1066 // Check if the left edge of the page is in the viewport
1067 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001068 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001069 if (mTmpIntPoint[0] >= viewportWidth) {
1070 break;
1071 }
1072 }
1073 range[0] = Math.max(0, leftScreen);
1074 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001075 } else {
1076 range[0] = -1;
1077 range[1] = -1;
1078 }
1079 }
1080
Michael Jurka920d7f42012-05-14 16:29:55 -07001081 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001082 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001083 }
1084
Michael Jurkadde558b2011-11-09 22:09:06 -08001085 @Override
1086 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001087 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001088 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1089 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001090 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001091
1092 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001093 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1094 // set it for the next frame
1095 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001096 screenScrolled(screenCenter);
1097 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001098 }
1099
1100 // Find out which screens are visible; as an optimization we only call draw on them
1101 final int pageCount = getChildCount();
1102 if (pageCount > 0) {
1103 getVisiblePages(mTempVisiblePagesRange);
1104 final int leftScreen = mTempVisiblePagesRange[0];
1105 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001106 if (leftScreen != -1 && rightScreen != -1) {
1107 final long drawingTime = getDrawingTime();
1108 // Clip to the bounds
1109 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001110 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1111 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001112
Adam Cohen7d30a372013-07-01 17:03:59 -07001113 // Draw all the children, leaving the drag view for last
1114 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001115 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001116 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001117 if (mForceDrawAllChildrenNextFrame ||
1118 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001119 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001120 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001121 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001122 // Draw the drag view on top (if there is one)
1123 if (mDragView != null) {
1124 drawChild(canvas, mDragView, drawingTime);
1125 }
1126
Michael Jurka5e368ff2012-05-14 23:13:15 -07001127 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001128 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001129 }
Michael Jurka0142d492010-08-25 17:46:15 -07001130 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001131 }
1132
1133 @Override
1134 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001135 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001136 if (page != mCurrentPage || !mScroller.isFinished()) {
1137 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001138 return true;
1139 }
1140 return false;
1141 }
1142
1143 @Override
1144 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001145 int focusablePage;
1146 if (mNextPage != INVALID_PAGE) {
1147 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001148 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001149 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001150 }
Winson Chung86f77532010-08-24 11:08:22 -07001151 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001152 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001153 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001154 }
1155 return false;
1156 }
1157
1158 @Override
1159 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001160 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001161 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001162 if (getCurrentPage() > 0) {
1163 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001164 return true;
1165 }
1166 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001167 if (getCurrentPage() < getPageCount() - 1) {
1168 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001169 return true;
1170 }
1171 }
1172 return super.dispatchUnhandledMove(focused, direction);
1173 }
1174
1175 @Override
1176 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001177 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001178 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001179 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001180 }
1181 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001182 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001183 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001184 }
1185 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001186 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001187 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001188 }
1189 }
1190 }
1191
1192 /**
1193 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001194 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001195 *
Winson Chung86f77532010-08-24 11:08:22 -07001196 * This happens when live folders requery, and if they're off page, they
1197 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001198 */
1199 @Override
1200 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001201 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001202 View v = focused;
1203 while (true) {
1204 if (v == current) {
1205 super.focusableViewAvailable(focused);
1206 return;
1207 }
1208 if (v == this) {
1209 return;
1210 }
1211 ViewParent parent = v.getParent();
1212 if (parent instanceof View) {
1213 v = (View)v.getParent();
1214 } else {
1215 return;
1216 }
1217 }
1218 }
1219
1220 /**
1221 * {@inheritDoc}
1222 */
1223 @Override
1224 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1225 if (disallowIntercept) {
1226 // We need to make sure to cancel our long press if
1227 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001228 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001229 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001230 }
1231 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1232 }
1233
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001234 /**
1235 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1236 */
1237 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001238 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001239 if (isLayoutRtl()) {
1240 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001241 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001242 }
Adam Cohenedb40762013-07-18 16:45:45 -07001243 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001244 }
1245
1246 /**
1247 * Return true if a tap at (x, y) should trigger a flip to the next page.
1248 */
1249 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001250 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001251 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001252 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001253 }
1254 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001255 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001256 }
Winson Chung52aee602013-01-30 12:01:02 -08001257
Adam Cohen7d30a372013-07-01 17:03:59 -07001258 /** Returns whether x and y originated within the buffered viewport */
1259 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1260 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1261 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1262 return mTmpRect.contains(x, y);
1263 }
1264
Winson Chung321e9ee2010-08-09 13:37:56 -07001265 @Override
1266 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001267 if (DISABLE_TOUCH_INTERACTION) {
1268 return false;
1269 }
1270
Winson Chung321e9ee2010-08-09 13:37:56 -07001271 /*
1272 * This method JUST determines whether we want to intercept the motion.
1273 * If we return true, onTouchEvent will be called and we do the actual
1274 * scrolling there.
1275 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001276 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001277
Winson Chung45e1d6e2010-11-09 17:19:49 -08001278 // Skip touch handling if there are no pages to swipe
1279 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1280
Winson Chung321e9ee2010-08-09 13:37:56 -07001281 /*
1282 * Shortcut the most recurring case: the user is in the dragging
1283 * state and he is moving his finger. We want to intercept this
1284 * motion.
1285 */
1286 final int action = ev.getAction();
1287 if ((action == MotionEvent.ACTION_MOVE) &&
1288 (mTouchState == TOUCH_STATE_SCROLLING)) {
1289 return true;
1290 }
1291
Winson Chung321e9ee2010-08-09 13:37:56 -07001292 switch (action & MotionEvent.ACTION_MASK) {
1293 case MotionEvent.ACTION_MOVE: {
1294 /*
1295 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1296 * whether the user has moved far enough from his original down touch.
1297 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001298 if (mActivePointerId != INVALID_POINTER) {
1299 determineScrollingStart(ev);
1300 break;
1301 }
1302 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1303 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1304 // i.e. fall through to the next case (don't break)
1305 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1306 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001307 }
1308
1309 case MotionEvent.ACTION_DOWN: {
1310 final float x = ev.getX();
1311 final float y = ev.getY();
1312 // Remember location of down touch
1313 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001314 mDownMotionY = y;
1315 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001316 mLastMotionX = x;
1317 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001318 float[] p = mapPointFromViewToParent(this, x, y);
1319 mParentDownMotionX = p[0];
1320 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001321 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001322 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001323 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001324
Winson Chung321e9ee2010-08-09 13:37:56 -07001325 /*
1326 * If being flinged and user touches the screen, initiate drag;
1327 * otherwise don't. mScroller.isFinished should be false when
1328 * being flinged.
1329 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001330 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001331 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1332 if (finishedScrolling) {
1333 mTouchState = TOUCH_STATE_REST;
1334 mScroller.abortAnimation();
1335 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001336 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1337 mTouchState = TOUCH_STATE_SCROLLING;
1338 } else {
1339 mTouchState = TOUCH_STATE_REST;
1340 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001341 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001342
Winson Chung86f77532010-08-24 11:08:22 -07001343 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001344 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001345 if (!DISABLE_TOUCH_SIDE_PAGES) {
1346 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1347 if (getChildCount() > 0) {
1348 if (hitsPreviousPage(x, y)) {
1349 mTouchState = TOUCH_STATE_PREV_PAGE;
1350 } else if (hitsNextPage(x, y)) {
1351 mTouchState = TOUCH_STATE_NEXT_PAGE;
1352 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001353 }
1354 }
1355 }
1356 break;
1357 }
1358
Winson Chung321e9ee2010-08-09 13:37:56 -07001359 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001360 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001361 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001362 break;
1363
1364 case MotionEvent.ACTION_POINTER_UP:
1365 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001366 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001367 break;
1368 }
1369
1370 /*
1371 * The only time we want to intercept motion events is if we are in the
1372 * drag mode.
1373 */
1374 return mTouchState != TOUCH_STATE_REST;
1375 }
1376
Adam Cohenf8d28232011-02-01 21:47:00 -08001377 protected void determineScrollingStart(MotionEvent ev) {
1378 determineScrollingStart(ev, 1.0f);
1379 }
1380
Winson Chung321e9ee2010-08-09 13:37:56 -07001381 /*
1382 * Determines if we should change the touch state to start scrolling after the
1383 * user moves their touch point too far.
1384 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001385 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001386 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001387 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001388 if (pointerIndex == -1) return;
1389
1390 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001391 final float x = ev.getX(pointerIndex);
1392 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001393 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1394
Winson Chung321e9ee2010-08-09 13:37:56 -07001395 final int xDiff = (int) Math.abs(x - mLastMotionX);
1396 final int yDiff = (int) Math.abs(y - mLastMotionY);
1397
Adam Cohenf8d28232011-02-01 21:47:00 -08001398 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001399 boolean xPaged = xDiff > mPagingTouchSlop;
1400 boolean xMoved = xDiff > touchSlop;
1401 boolean yMoved = yDiff > touchSlop;
1402
Adam Cohenf8d28232011-02-01 21:47:00 -08001403 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001404 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001405 // Scroll if the user moved far enough along the X axis
1406 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001407 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001408 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001409 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001410 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001411 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1412 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001413 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001414 }
1415 }
1416
Adam Cohen7d30a372013-07-01 17:03:59 -07001417 protected float getMaxScrollProgress() {
1418 return 1.0f;
1419 }
1420
Adam Cohenf8d28232011-02-01 21:47:00 -08001421 protected void cancelCurrentPageLongPress() {
1422 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001423 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001424 // Try canceling the long press. It could also have been scheduled
1425 // by a distant descendant, so use the mAllowLongPress flag to block
1426 // everything
1427 final View currentPage = getPageAt(mCurrentPage);
1428 if (currentPage != null) {
1429 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001430 }
1431 }
1432 }
1433
Adam Cohen7d30a372013-07-01 17:03:59 -07001434 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1435 final int halfScreenSize = getViewportWidth() / 2;
1436
1437 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1438 screenCenter = Math.max(halfScreenSize, screenCenter);
1439
1440 return getScrollProgress(screenCenter, v, page);
1441 }
1442
Adam Cohenb5ba0972011-09-07 18:02:31 -07001443 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001444 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001445
Adam Cohen96d30a12013-07-16 18:13:21 -07001446 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001447 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001448
1449 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001450 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1451 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001452 return scrollProgress;
1453 }
1454
Adam Cohenedb40762013-07-18 16:45:45 -07001455 public int getScrollForPage(int index) {
1456 if (mPageScrolls == null || index >= mPageScrolls.length) {
1457 return 0;
1458 } else {
1459 return mPageScrolls[index];
1460 }
1461 }
1462
Adam Cohene0f66b52010-11-23 15:06:07 -08001463 // This curve determines how the effect of scrolling over the limits of the page dimishes
1464 // as the user pulls further and further from the bounds
1465 private float overScrollInfluenceCurve(float f) {
1466 f -= 1.0f;
1467 return f * f * f + 1.0f;
1468 }
1469
Adam Cohenb5ba0972011-09-07 18:02:31 -07001470 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001471 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001472
1473 // We want to reach the max over scroll effect when the user has
1474 // over scrolled half the size of the screen
1475 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1476
1477 if (f == 0) return;
1478
1479 // Clamp this factor, f, to -1 < f < 1
1480 if (Math.abs(f) >= 1) {
1481 f /= Math.abs(f);
1482 }
1483
1484 int overScrollAmount = (int) Math.round(f * screenSize);
1485 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001486 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001487 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001488 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001489 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001490 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001491 }
1492 invalidate();
1493 }
1494
1495 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001496 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001497
1498 float f = (amount / screenSize);
1499
1500 if (f == 0) return;
1501 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1502
Adam Cohen7bfc9792011-01-28 13:52:37 -08001503 // Clamp this factor, f, to -1 < f < 1
1504 if (Math.abs(f) >= 1) {
1505 f /= Math.abs(f);
1506 }
1507
Adam Cohene0f66b52010-11-23 15:06:07 -08001508 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001509 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001510 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001511 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001512 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001513 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001514 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001515 }
1516 invalidate();
1517 }
1518
Adam Cohenb5ba0972011-09-07 18:02:31 -07001519 protected void overScroll(float amount) {
1520 dampedOverScroll(amount);
1521 }
1522
Michael Jurkac5b262c2011-01-12 20:24:50 -08001523 protected float maxOverScroll() {
1524 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001525 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001526 float f = 1.0f;
1527 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1528 return OVERSCROLL_DAMP_FACTOR * f;
1529 }
1530
Adam Cohenf358a4b2013-07-23 16:47:31 -07001531 protected void enableFreeScroll() {
1532 setEnableFreeScroll(true, -1);
1533 }
1534
1535 protected void disableFreeScroll(int snapPage) {
1536 setEnableFreeScroll(false, snapPage);
1537 }
1538
1539 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1540 mFreeScroll = freeScroll;
1541
1542 if (snapPage == -1) {
1543 snapPage = getPageNearestToCenterOfScreen();
1544 }
1545
1546 getOverviewModePages(mTempVisiblePagesRange);
1547 if (!mFreeScroll) {
1548 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001549 } else {
1550 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1551 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1552
Adam Cohenf358a4b2013-07-23 16:47:31 -07001553 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1554 setCurrentPage(mTempVisiblePagesRange[0]);
1555 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1556 setCurrentPage(mTempVisiblePagesRange[1]);
1557 }
1558 }
1559
1560 setEnableOverscroll(!freeScroll);
1561 }
1562
1563 private void setEnableOverscroll(boolean enable) {
1564 mAllowOverScroll = enable;
1565 }
1566
1567 int getNearestHoverOverPageIndex() {
1568 if (mDragView != null) {
1569 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1570 + mDragView.getTranslationX());
1571 getOverviewModePages(mTempVisiblePagesRange);
1572 int minDistance = Integer.MAX_VALUE;
1573 int minIndex = indexOfChild(mDragView);
1574 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1575 View page = getPageAt(i);
1576 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1577 int d = Math.abs(dragX - pageX);
1578 if (d < minDistance) {
1579 minIndex = i;
1580 minDistance = d;
1581 }
1582 }
1583 return minIndex;
1584 }
1585 return -1;
1586 }
1587
Winson Chung321e9ee2010-08-09 13:37:56 -07001588 @Override
1589 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001590 if (DISABLE_TOUCH_INTERACTION) {
1591 return false;
1592 }
1593
Winson Chung45e1d6e2010-11-09 17:19:49 -08001594 // Skip touch handling if there are no pages to swipe
1595 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1596
Michael Jurkab8f06722010-10-10 15:58:46 -07001597 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001598
1599 final int action = ev.getAction();
1600
1601 switch (action & MotionEvent.ACTION_MASK) {
1602 case MotionEvent.ACTION_DOWN:
1603 /*
1604 * If being flinged and user touches, stop the fling. isFinished
1605 * will be false if being flinged.
1606 */
1607 if (!mScroller.isFinished()) {
1608 mScroller.abortAnimation();
1609 }
1610
1611 // Remember where the motion event started
1612 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001613 mDownMotionY = mLastMotionY = ev.getY();
1614 mDownScrollX = getScrollX();
1615 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1616 mParentDownMotionX = p[0];
1617 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001618 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001619 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001620 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001621
Michael Jurka0142d492010-08-25 17:46:15 -07001622 if (mTouchState == TOUCH_STATE_SCROLLING) {
1623 pageBeginMoving();
1624 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001625 break;
1626
1627 case MotionEvent.ACTION_MOVE:
1628 if (mTouchState == TOUCH_STATE_SCROLLING) {
1629 // Scroll to follow the motion event
1630 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001631
1632 if (pointerIndex == -1) return true;
1633
Winson Chung321e9ee2010-08-09 13:37:56 -07001634 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001635 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001636
Adam Cohenaefd4e12011-02-14 16:39:38 -08001637 mTotalMotionX += Math.abs(deltaX);
1638
Winson Chungc0844aa2011-02-02 15:25:58 -08001639 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1640 // keep the remainder because we are actually testing if we've moved from the last
1641 // scrolled position (which is discrete).
1642 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001643 mTouchX += deltaX;
1644 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1645 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001646 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001647 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001648 } else {
1649 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001650 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001651 mLastMotionX = x;
1652 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001653 } else {
1654 awakenScrollBars();
1655 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001656 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1657 // Update the last motion position
1658 mLastMotionX = ev.getX();
1659 mLastMotionY = ev.getY();
1660
1661 // Update the parent down so that our zoom animations take this new movement into
1662 // account
1663 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1664 mParentDownMotionX = pt[0];
1665 mParentDownMotionY = pt[1];
1666 updateDragViewTranslationDuringDrag();
1667
1668 // Find the closest page to the touch point
1669 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001670
1671 // Change the drag view if we are hovering over the drop target
1672 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1673 (int) mParentDownMotionX, (int) mParentDownMotionY);
1674 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1675
Adam Cohen7d30a372013-07-01 17:03:59 -07001676 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1677 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1678 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1679 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1680
Adam Cohenf358a4b2013-07-23 16:47:31 -07001681 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1682 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1683 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001684 mTempVisiblePagesRange[0] = 0;
1685 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001686 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001687 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1688 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1689 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1690 mSidePageHoverIndex = pageUnderPointIndex;
1691 mSidePageHoverRunnable = new Runnable() {
1692 @Override
1693 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001694 // Setup the scroll to the correct page before we swap the views
1695 snapToPage(pageUnderPointIndex);
1696
1697 // For each of the pages between the paged view and the drag view,
1698 // animate them from the previous position to the new position in
1699 // the layout (as a result of the drag view moving in the layout)
1700 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1701 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1702 dragViewIndex + 1 : pageUnderPointIndex;
1703 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1704 dragViewIndex - 1 : pageUnderPointIndex;
1705 for (int i = lowerIndex; i <= upperIndex; ++i) {
1706 View v = getChildAt(i);
1707 // dragViewIndex < pageUnderPointIndex, so after we remove the
1708 // drag view all subsequent views to pageUnderPointIndex will
1709 // shift down.
1710 int oldX = getViewportOffsetX() + getChildOffset(i);
1711 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1712
1713 // Animate the view translation from its old position to its new
1714 // position
1715 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1716 if (anim != null) {
1717 anim.cancel();
1718 }
1719
1720 v.setTranslationX(oldX - newX);
1721 anim = new AnimatorSet();
1722 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1723 anim.playTogether(
1724 ObjectAnimator.ofFloat(v, "translationX", 0f));
1725 anim.start();
1726 v.setTag(anim);
1727 }
1728
1729 removeView(mDragView);
1730 onRemoveView(mDragView, false);
1731 addView(mDragView, pageUnderPointIndex);
1732 onAddView(mDragView, pageUnderPointIndex);
1733 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001734 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001735 }
1736 };
1737 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1738 }
1739 } else {
1740 removeCallbacks(mSidePageHoverRunnable);
1741 mSidePageHoverIndex = -1;
1742 }
Adam Cohen564976a2010-10-13 18:52:07 -07001743 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001744 determineScrollingStart(ev);
1745 }
1746 break;
1747
1748 case MotionEvent.ACTION_UP:
1749 if (mTouchState == TOUCH_STATE_SCROLLING) {
1750 final int activePointerId = mActivePointerId;
1751 final int pointerIndex = ev.findPointerIndex(activePointerId);
1752 final float x = ev.getX(pointerIndex);
1753 final VelocityTracker velocityTracker = mVelocityTracker;
1754 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1755 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001756 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001757 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001758 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1759 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001760
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001761 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1762
Adam Cohen00481b32011-11-18 12:03:48 -08001763 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001764 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001765
Adam Cohenf358a4b2013-07-23 16:47:31 -07001766 if (!mFreeScroll) {
1767 // In the case that the page is moved far to one direction and then is flung
1768 // in the opposite direction, we use a threshold to determine whether we should
1769 // just return to the starting page, or if we should skip one further.
1770 boolean returnToOriginalPage = false;
1771 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1772 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1773 returnToOriginalPage = true;
1774 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001775
Adam Cohenf358a4b2013-07-23 16:47:31 -07001776 int finalPage;
1777 // We give flings precedence over large moves, which is why we short-circuit our
1778 // test for a large move if a fling has been registered. That is, a large
1779 // move to the left and fling to the right will register as a fling to the right.
1780 final boolean isRtl = isLayoutRtl();
1781 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1782 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1783 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1784 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1785 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1786 snapToPageWithVelocity(finalPage, velocityX);
1787 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1788 (isFling && isVelocityXLeft)) &&
1789 mCurrentPage < getChildCount() - 1) {
1790 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1791 snapToPageWithVelocity(finalPage, velocityX);
1792 } else {
1793 snapToDestination();
1794 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1795 // at this point we have not moved beyond the touch slop
1796 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1797 // we can just page
1798 int nextPage = Math.max(0, mCurrentPage - 1);
1799 if (nextPage != mCurrentPage) {
1800 snapToPage(nextPage);
1801 } else {
1802 snapToDestination();
1803 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001804 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001805 if (!mScroller.isFinished()) {
1806 mScroller.abortAnimation();
1807 }
1808
1809 float scaleX = getScaleX();
1810 int vX = (int) (-velocityX * scaleX);
1811 int initialScrollX = (int) (getScrollX() * scaleX);
1812
1813 mScroller.fling(initialScrollX,
1814 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1815 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001816 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001817 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001818 // at this point we have not moved beyond the touch slop
1819 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1820 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001821 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1822 if (nextPage != mCurrentPage) {
1823 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001824 } else {
1825 snapToDestination();
1826 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001827 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1828 // Update the last motion position
1829 mLastMotionX = ev.getX();
1830 mLastMotionY = ev.getY();
1831
1832 // Update the parent down so that our zoom animations take this new movement into
1833 // account
1834 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1835 mParentDownMotionX = pt[0];
1836 mParentDownMotionY = pt[1];
1837 updateDragViewTranslationDuringDrag();
1838 boolean handledFling = false;
1839 if (!DISABLE_FLING_TO_DELETE) {
1840 // Check the velocity and see if we are flinging-to-delete
1841 PointF flingToDeleteVector = isFlingingToDelete();
1842 if (flingToDeleteVector != null) {
1843 onFlingToDelete(flingToDeleteVector);
1844 handledFling = true;
1845 }
1846 }
1847 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1848 (int) mParentDownMotionY)) {
1849 onDropToDelete();
1850 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001851 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001852 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001853 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001854
1855 // Remove the callback to wait for the side page hover timeout
1856 removeCallbacks(mSidePageHoverRunnable);
1857 // End any intermediate reordering states
1858 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001859 break;
1860
1861 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001862 if (mTouchState == TOUCH_STATE_SCROLLING) {
1863 snapToDestination();
1864 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001865 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001866 break;
1867
1868 case MotionEvent.ACTION_POINTER_UP:
1869 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001870 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001871 break;
1872 }
1873
1874 return true;
1875 }
1876
Adam Cohen7d30a372013-07-01 17:03:59 -07001877 public void onFlingToDelete(View v) {}
1878 public void onRemoveView(View v, boolean deletePermanently) {}
1879 public void onRemoveViewAnimationCompleted() {}
1880 public void onAddView(View v, int index) {}
1881
1882 private void resetTouchState() {
1883 releaseVelocityTracker();
1884 endReordering();
1885 mTouchState = TOUCH_STATE_REST;
1886 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001887 }
1888
1889 protected void onUnhandledTap(MotionEvent ev) {}
1890
Winson Chung185d7162011-02-28 13:47:29 -08001891 @Override
1892 public boolean onGenericMotionEvent(MotionEvent event) {
1893 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1894 switch (event.getAction()) {
1895 case MotionEvent.ACTION_SCROLL: {
1896 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1897 final float vscroll;
1898 final float hscroll;
1899 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1900 vscroll = 0;
1901 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1902 } else {
1903 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1904 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1905 }
1906 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001907 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1908 : (hscroll > 0 || vscroll > 0);
1909 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001910 scrollRight();
1911 } else {
1912 scrollLeft();
1913 }
1914 return true;
1915 }
1916 }
1917 }
1918 }
1919 return super.onGenericMotionEvent(event);
1920 }
1921
Michael Jurkab8f06722010-10-10 15:58:46 -07001922 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1923 if (mVelocityTracker == null) {
1924 mVelocityTracker = VelocityTracker.obtain();
1925 }
1926 mVelocityTracker.addMovement(ev);
1927 }
1928
1929 private void releaseVelocityTracker() {
1930 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001931 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001932 mVelocityTracker.recycle();
1933 mVelocityTracker = null;
1934 }
1935 }
1936
Winson Chung321e9ee2010-08-09 13:37:56 -07001937 private void onSecondaryPointerUp(MotionEvent ev) {
1938 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1939 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1940 final int pointerId = ev.getPointerId(pointerIndex);
1941 if (pointerId == mActivePointerId) {
1942 // This was our active pointer going up. Choose a new
1943 // active pointer and adjust accordingly.
1944 // TODO: Make this decision more intelligent.
1945 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1946 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1947 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001948 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001949 mActivePointerId = ev.getPointerId(newPointerIndex);
1950 if (mVelocityTracker != null) {
1951 mVelocityTracker.clear();
1952 }
1953 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001954 }
1955
Winson Chung321e9ee2010-08-09 13:37:56 -07001956 @Override
1957 public void requestChildFocus(View child, View focused) {
1958 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001959 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001960 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001961 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001962 }
1963 }
1964
Winson Chung1908d072011-02-24 18:09:44 -08001965 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001966 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001967 }
1968
Adam Cohen7d30a372013-07-01 17:03:59 -07001969 int getPageNearestToPoint(float x) {
1970 int index = 0;
1971 for (int i = 0; i < getChildCount(); ++i) {
1972 if (x < getChildAt(i).getRight() - getScrollX()) {
1973 return index;
1974 } else {
1975 index++;
1976 }
1977 }
1978 return Math.min(index, getChildCount() - 1);
1979 }
1980
Adam Cohend19d3ca2010-09-15 14:43:42 -07001981 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001982 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001983 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001984 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001985 final int childCount = getChildCount();
1986 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001987 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001988 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001989 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001990 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001991 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1992 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1993 minDistanceFromScreenCenter = distanceFromScreenCenter;
1994 minDistanceFromScreenCenterIndex = i;
1995 }
1996 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001997 return minDistanceFromScreenCenterIndex;
1998 }
1999
2000 protected void snapToDestination() {
2001 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002002 }
2003
Adam Cohene0f66b52010-11-23 15:06:07 -08002004 private static class ScrollInterpolator implements Interpolator {
2005 public ScrollInterpolator() {
2006 }
2007
2008 public float getInterpolation(float t) {
2009 t -= 1.0f;
2010 return t*t*t*t*t + 1;
2011 }
2012 }
2013
2014 // We want the duration of the page snap animation to be influenced by the distance that
2015 // the screen has to travel, however, we don't want this duration to be effected in a
2016 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2017 // of travel has on the overall snap duration.
2018 float distanceInfluenceForSnapDuration(float f) {
2019 f -= 0.5f; // center the values about 0.
2020 f *= 0.3f * Math.PI / 2.0f;
2021 return (float) Math.sin(f);
2022 }
2023
Michael Jurka0142d492010-08-25 17:46:15 -07002024 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002025 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002026 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002027
Adam Cohenedb40762013-07-18 16:45:45 -07002028 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002029 int delta = newX - mUnboundedScrollX;
2030 int duration = 0;
2031
Adam Cohen265b9a62011-12-07 14:37:18 -08002032 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002033 // If the velocity is low enough, then treat this more as an automatic page advance
2034 // as opposed to an apparent physical response to flinging
2035 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2036 return;
2037 }
2038
2039 // Here we compute a "distance" that will be used in the computation of the overall
2040 // snap duration. This is a function of the actual distance that needs to be traveled;
2041 // we keep this value close to half screen size in order to reduce the variance in snap
2042 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002043 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002044 float distance = halfScreenSize + halfScreenSize *
2045 distanceInfluenceForSnapDuration(distanceRatio);
2046
2047 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002048 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002049
2050 // we want the page's snap velocity to approximately match the velocity at which the
2051 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002052 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2053 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002054
2055 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002056 }
2057
2058 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002059 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002060 }
2061
Adam Cohen7d30a372013-07-01 17:03:59 -07002062 protected void snapToPageImmediately(int whichPage) {
2063 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2064 }
2065
Michael Jurka0142d492010-08-25 17:46:15 -07002066 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002067 snapToPage(whichPage, duration, false);
2068 }
2069
2070 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002071 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002072
Adam Cohenedb40762013-07-18 16:45:45 -07002073 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002074 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002075 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002076 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002077 }
2078
2079 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002080 snapToPage(whichPage, delta, duration, false);
2081 }
Michael Jurka0142d492010-08-25 17:46:15 -07002082
Adam Cohen7d30a372013-07-01 17:03:59 -07002083 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2084 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002085 View focusedChild = getFocusedChild();
2086 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002087 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002088 focusedChild.clearFocus();
2089 }
2090
2091 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002092 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002093 if (immediate) {
2094 duration = 0;
2095 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002096 duration = Math.abs(delta);
2097 }
2098
Adam Cohenf358a4b2013-07-23 16:47:31 -07002099 if (!mScroller.isFinished()) {
2100 mScroller.abortAnimation();
2101 }
Adam Cohen68d73932010-11-15 10:50:58 -08002102 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002103
Michael Jurka0142d492010-08-25 17:46:15 -07002104 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002105
2106 // Trigger a compute() to finish switching pages if necessary
2107 if (immediate) {
2108 computeScroll();
2109 }
2110
Winson Chung9c0565f2013-07-19 13:49:06 -07002111 // Defer loading associated pages until the scroll settles
2112 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2113
Adam Cohen7d30a372013-07-01 17:03:59 -07002114 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002115 invalidate();
2116 }
2117
Winson Chung321e9ee2010-08-09 13:37:56 -07002118 public void scrollLeft() {
2119 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002120 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002121 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002122 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002123 }
2124 }
2125
2126 public void scrollRight() {
2127 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002128 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002129 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002130 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002131 }
2132 }
2133
Winson Chung86f77532010-08-24 11:08:22 -07002134 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002135 int result = -1;
2136 if (v != null) {
2137 ViewParent vp = v.getParent();
2138 int count = getChildCount();
2139 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002140 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002141 return i;
2142 }
2143 }
2144 }
2145 return result;
2146 }
2147
2148 /**
2149 * @return True is long presses are still allowed for the current touch
2150 */
2151 public boolean allowLongPress() {
2152 return mAllowLongPress;
2153 }
2154
Michael Jurka0142d492010-08-25 17:46:15 -07002155 /**
2156 * Set true to allow long-press events to be triggered, usually checked by
2157 * {@link Launcher} to accept or block dpad-initiated long-presses.
2158 */
2159 public void setAllowLongPress(boolean allowLongPress) {
2160 mAllowLongPress = allowLongPress;
2161 }
2162
Winson Chung321e9ee2010-08-09 13:37:56 -07002163 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002164 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002165
2166 SavedState(Parcelable superState) {
2167 super(superState);
2168 }
2169
2170 private SavedState(Parcel in) {
2171 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002172 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002173 }
2174
2175 @Override
2176 public void writeToParcel(Parcel out, int flags) {
2177 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002178 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002179 }
2180
2181 public static final Parcelable.Creator<SavedState> CREATOR =
2182 new Parcelable.Creator<SavedState>() {
2183 public SavedState createFromParcel(Parcel in) {
2184 return new SavedState(in);
2185 }
2186
2187 public SavedState[] newArray(int size) {
2188 return new SavedState[size];
2189 }
2190 };
2191 }
2192
Winson Chungf314b0e2011-08-16 11:54:27 -07002193 protected void loadAssociatedPages(int page) {
2194 loadAssociatedPages(page, false);
2195 }
2196 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002197 if (mContentIsRefreshable) {
2198 final int count = getChildCount();
2199 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002200 int lowerPageBound = getAssociatedLowerPageBound(page);
2201 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002202 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2203 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002204 // First, clear any pages that should no longer be loaded
2205 for (int i = 0; i < count; ++i) {
2206 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002207 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002208 if (layout.getPageChildCount() > 0) {
2209 layout.removeAllViewsOnPage();
2210 }
2211 mDirtyPageContent.set(i, true);
2212 }
2213 }
2214 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002215 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002216 if ((i != page) && immediateAndOnly) {
2217 continue;
2218 }
Michael Jurka0142d492010-08-25 17:46:15 -07002219 if (lowerPageBound <= i && i <= upperPageBound) {
2220 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002221 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002222 mDirtyPageContent.set(i, false);
2223 }
Winson Chung86f77532010-08-24 11:08:22 -07002224 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002225 }
2226 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002227 }
2228 }
2229
Winson Chunge3193b92010-09-10 11:44:42 -07002230 protected int getAssociatedLowerPageBound(int page) {
2231 return Math.max(0, page - 1);
2232 }
2233 protected int getAssociatedUpperPageBound(int page) {
2234 final int count = getChildCount();
2235 return Math.min(page + 1, count - 1);
2236 }
2237
Winson Chung86f77532010-08-24 11:08:22 -07002238 /**
2239 * This method is called ONLY to synchronize the number of pages that the paged view has.
2240 * To actually fill the pages with information, implement syncPageItems() below. It is
2241 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2242 * and therefore, individual page items do not need to be updated in this method.
2243 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002244 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002245
2246 /**
2247 * This method is called to synchronize the items that are on a particular page. If views on
2248 * the page can be reused, then they should be updated within this method.
2249 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002250 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002251
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002252 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002253 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002254 }
2255 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002256 invalidatePageData(currentPage, false);
2257 }
2258 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002259 if (!mIsDataReady) {
2260 return;
2261 }
2262
Michael Jurka0142d492010-08-25 17:46:15 -07002263 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002264 // Force all scrolling-related behavior to end
2265 mScroller.forceFinished(true);
2266 mNextPage = INVALID_PAGE;
2267
Michael Jurka0142d492010-08-25 17:46:15 -07002268 // Update all the pages
2269 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002270
Winson Chung5a808352011-06-27 19:08:49 -07002271 // We must force a measure after we've loaded the pages to update the content width and
2272 // to determine the full scroll width
2273 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2274 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2275
2276 // Set a new page as the current page if necessary
2277 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002278 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002279 }
2280
Michael Jurka0142d492010-08-25 17:46:15 -07002281 // Mark each of the pages as dirty
2282 final int count = getChildCount();
2283 mDirtyPageContent.clear();
2284 for (int i = 0; i < count; ++i) {
2285 mDirtyPageContent.add(true);
2286 }
2287
2288 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002289 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002290 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002291 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002292 }
Winson Chung007c6982011-06-14 13:27:53 -07002293
Adam Cohen7d30a372013-07-01 17:03:59 -07002294 // Animate the drag view back to the original position
2295 void animateDragViewToOriginalPosition() {
2296 if (mDragView != null) {
2297 AnimatorSet anim = new AnimatorSet();
2298 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2299 anim.playTogether(
2300 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002301 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2302 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2303 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002304 anim.addListener(new AnimatorListenerAdapter() {
2305 @Override
2306 public void onAnimationEnd(Animator animation) {
2307 onPostReorderingAnimationCompleted();
2308 }
2309 });
2310 anim.start();
2311 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002312 }
2313
Adam Cohen7d30a372013-07-01 17:03:59 -07002314 protected void onStartReordering() {
2315 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2316 mTouchState = TOUCH_STATE_REORDERING;
2317 mIsReordering = true;
2318
Adam Cohen7d30a372013-07-01 17:03:59 -07002319 // We must invalidate to trigger a redraw to update the layers such that the drag view
2320 // is always drawn on top
2321 invalidate();
2322 }
2323
2324 private void onPostReorderingAnimationCompleted() {
2325 // Trigger the callback when reordering has settled
2326 --mPostReorderingPreZoomInRemainingAnimationCount;
2327 if (mPostReorderingPreZoomInRunnable != null &&
2328 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2329 mPostReorderingPreZoomInRunnable.run();
2330 mPostReorderingPreZoomInRunnable = null;
2331 }
2332 }
2333
2334 protected void onEndReordering() {
2335 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002336 }
2337
Adam Cohenf358a4b2013-07-23 16:47:31 -07002338 public boolean startReordering(View v) {
2339 int dragViewIndex = indexOfChild(v);//getPageNearestToCenterOfScreen();
Adam Cohen7d30a372013-07-01 17:03:59 -07002340 mTempVisiblePagesRange[0] = 0;
2341 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002342 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002343 mReorderingStarted = true;
2344
2345 // Check if we are within the reordering range
2346 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002347 dragViewIndex <= mTempVisiblePagesRange[1]) {
2348 // Find the drag view under the pointer
2349 mDragView = getChildAt(dragViewIndex);
2350 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2351 mDragViewBaselineLeft = mDragView.getLeft();
2352 disableFreeScroll(-1);
2353 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002354 return true;
2355 }
2356 return false;
2357 }
2358
2359 boolean isReordering(boolean testTouchState) {
2360 boolean state = mIsReordering;
2361 if (testTouchState) {
2362 state &= (mTouchState == TOUCH_STATE_REORDERING);
2363 }
2364 return state;
2365 }
2366 void endReordering() {
2367 // For simplicity, we call endReordering sometimes even if reordering was never started.
2368 // In that case, we don't want to do anything.
2369 if (!mReorderingStarted) return;
2370 mReorderingStarted = false;
2371
2372 // If we haven't flung-to-delete the current child, then we just animate the drag view
2373 // back into position
2374 final Runnable onCompleteRunnable = new Runnable() {
2375 @Override
2376 public void run() {
2377 onEndReordering();
2378 }
2379 };
2380 if (!mDeferringForDelete) {
2381 mPostReorderingPreZoomInRunnable = new Runnable() {
2382 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002383 onCompleteRunnable.run();
2384 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002385 };
2386 };
2387
2388 mPostReorderingPreZoomInRemainingAnimationCount =
2389 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2390 // Snap to the current page
2391 snapToPage(indexOfChild(mDragView), 0);
2392 // Animate the drag view back to the front position
2393 animateDragViewToOriginalPosition();
2394 } else {
2395 // Handled in post-delete-animation-callbacks
2396 }
2397 }
2398
Adam Cohen7d30a372013-07-01 17:03:59 -07002399 /*
2400 * Flinging to delete - IN PROGRESS
2401 */
2402 private PointF isFlingingToDelete() {
2403 ViewConfiguration config = ViewConfiguration.get(getContext());
2404 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2405
2406 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2407 // Do a quick dot product test to ensure that we are flinging upwards
2408 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2409 mVelocityTracker.getYVelocity());
2410 PointF upVec = new PointF(0f, -1f);
2411 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2412 (vel.length() * upVec.length()));
2413 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2414 return vel;
2415 }
2416 }
2417 return null;
2418 }
2419
2420 /**
2421 * Creates an animation from the current drag view along its current velocity vector.
2422 * For this animation, the alpha runs for a fixed duration and we update the position
2423 * progressively.
2424 */
2425 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2426 private View mDragView;
2427 private PointF mVelocity;
2428 private Rect mFrom;
2429 private long mPrevTime;
2430 private float mFriction;
2431
2432 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2433
2434 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2435 long startTime, float friction) {
2436 mDragView = dragView;
2437 mVelocity = vel;
2438 mFrom = from;
2439 mPrevTime = startTime;
2440 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2441 }
2442
2443 @Override
2444 public void onAnimationUpdate(ValueAnimator animation) {
2445 float t = ((Float) animation.getAnimatedValue()).floatValue();
2446 long curTime = AnimationUtils.currentAnimationTimeMillis();
2447
2448 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2449 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2450
2451 mDragView.setTranslationX(mFrom.left);
2452 mDragView.setTranslationY(mFrom.top);
2453 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2454
2455 mVelocity.x *= mFriction;
2456 mVelocity.y *= mFriction;
2457 mPrevTime = curTime;
2458 }
2459 };
2460
2461 private static final int ANIM_TAG_KEY = 100;
2462
2463 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2464 return new Runnable() {
2465 @Override
2466 public void run() {
2467 int dragViewIndex = indexOfChild(dragView);
2468
2469 // For each of the pages around the drag view, animate them from the previous
2470 // position to the new position in the layout (as a result of the drag view moving
2471 // in the layout)
2472 // NOTE: We can make an assumption here because we have side-bound pages that we
2473 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002474 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002475 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2476 boolean slideFromLeft = (isLastWidgetPage ||
2477 dragViewIndex > mTempVisiblePagesRange[0]);
2478
2479 // Setup the scroll to the correct page before we swap the views
2480 if (slideFromLeft) {
2481 snapToPageImmediately(dragViewIndex - 1);
2482 }
2483
2484 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2485 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2486 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2487 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2488 ArrayList<Animator> animations = new ArrayList<Animator>();
2489 for (int i = lowerIndex; i <= upperIndex; ++i) {
2490 View v = getChildAt(i);
2491 // dragViewIndex < pageUnderPointIndex, so after we remove the
2492 // drag view all subsequent views to pageUnderPointIndex will
2493 // shift down.
2494 int oldX = 0;
2495 int newX = 0;
2496 if (slideFromLeft) {
2497 if (i == 0) {
2498 // Simulate the page being offscreen with the page spacing
2499 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2500 - mPageSpacing;
2501 } else {
2502 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2503 }
2504 newX = getViewportOffsetX() + getChildOffset(i);
2505 } else {
2506 oldX = getChildOffset(i) - getChildOffset(i - 1);
2507 newX = 0;
2508 }
2509
2510 // Animate the view translation from its old position to its new
2511 // position
2512 AnimatorSet anim = (AnimatorSet) v.getTag();
2513 if (anim != null) {
2514 anim.cancel();
2515 }
2516
2517 // Note: Hacky, but we want to skip any optimizations to not draw completely
2518 // hidden views
2519 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2520 v.setTranslationX(oldX - newX);
2521 anim = new AnimatorSet();
2522 anim.playTogether(
2523 ObjectAnimator.ofFloat(v, "translationX", 0f),
2524 ObjectAnimator.ofFloat(v, "alpha", 1f));
2525 animations.add(anim);
2526 v.setTag(ANIM_TAG_KEY, anim);
2527 }
2528
2529 AnimatorSet slideAnimations = new AnimatorSet();
2530 slideAnimations.playTogether(animations);
2531 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2532 slideAnimations.addListener(new AnimatorListenerAdapter() {
2533 @Override
2534 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002535 mDeferringForDelete = false;
2536 onEndReordering();
2537 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002538 }
2539 });
2540 slideAnimations.start();
2541
2542 removeView(dragView);
2543 onRemoveView(dragView, true);
2544 }
2545 };
2546 }
2547
2548 public void onFlingToDelete(PointF vel) {
2549 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2550
2551 // NOTE: Because it takes time for the first frame of animation to actually be
2552 // called and we expect the animation to be a continuation of the fling, we have
2553 // to account for the time that has elapsed since the fling finished. And since
2554 // we don't have a startDelay, we will always get call to update when we call
2555 // start() (which we want to ignore).
2556 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2557 private int mCount = -1;
2558 private long mStartTime;
2559 private float mOffset;
2560 /* Anonymous inner class ctor */ {
2561 mStartTime = startTime;
2562 }
2563
2564 @Override
2565 public float getInterpolation(float t) {
2566 if (mCount < 0) {
2567 mCount++;
2568 } else if (mCount == 0) {
2569 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2570 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2571 mCount++;
2572 }
2573 return Math.min(1f, mOffset + t);
2574 }
2575 };
2576
2577 final Rect from = new Rect();
2578 final View dragView = mDragView;
2579 from.left = (int) dragView.getTranslationX();
2580 from.top = (int) dragView.getTranslationY();
2581 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2582 from, startTime, FLING_TO_DELETE_FRICTION);
2583
2584 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2585
2586 // Create and start the animation
2587 ValueAnimator mDropAnim = new ValueAnimator();
2588 mDropAnim.setInterpolator(tInterpolator);
2589 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2590 mDropAnim.setFloatValues(0f, 1f);
2591 mDropAnim.addUpdateListener(updateCb);
2592 mDropAnim.addListener(new AnimatorListenerAdapter() {
2593 public void onAnimationEnd(Animator animation) {
2594 onAnimationEndRunnable.run();
2595 }
2596 });
2597 mDropAnim.start();
2598 mDeferringForDelete = true;
2599 }
2600
2601 /* Drag to delete */
2602 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2603 if (mDeleteDropTarget != null) {
2604 mAltTmpRect.set(0, 0, 0, 0);
2605 View parent = (View) mDeleteDropTarget.getParent();
2606 if (parent != null) {
2607 parent.getGlobalVisibleRect(mAltTmpRect);
2608 }
2609 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2610 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2611 return mTmpRect.contains(x, y);
2612 }
2613 return false;
2614 }
2615
2616 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2617
2618 private void onDropToDelete() {
2619 final View dragView = mDragView;
2620
2621 final float toScale = 0f;
2622 final float toAlpha = 0f;
2623
2624 // Create and start the complex animation
2625 ArrayList<Animator> animations = new ArrayList<Animator>();
2626 AnimatorSet motionAnim = new AnimatorSet();
2627 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2628 motionAnim.playTogether(
2629 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2630 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2631 animations.add(motionAnim);
2632
2633 AnimatorSet alphaAnim = new AnimatorSet();
2634 alphaAnim.setInterpolator(new LinearInterpolator());
2635 alphaAnim.playTogether(
2636 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2637 animations.add(alphaAnim);
2638
2639 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2640
2641 AnimatorSet anim = new AnimatorSet();
2642 anim.playTogether(animations);
2643 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2644 anim.addListener(new AnimatorListenerAdapter() {
2645 public void onAnimationEnd(Animator animation) {
2646 onAnimationEndRunnable.run();
2647 }
2648 });
2649 anim.start();
2650
2651 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002652 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002653
2654 /* Accessibility */
2655 @Override
2656 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2657 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002658 info.setScrollable(getPageCount() > 1);
2659 if (getCurrentPage() < getPageCount() - 1) {
2660 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2661 }
2662 if (getCurrentPage() > 0) {
2663 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2664 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002665 }
2666
2667 @Override
2668 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2669 super.onInitializeAccessibilityEvent(event);
2670 event.setScrollable(true);
2671 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2672 event.setFromIndex(mCurrentPage);
2673 event.setToIndex(mCurrentPage);
2674 event.setItemCount(getChildCount());
2675 }
2676 }
2677
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002678 @Override
2679 public boolean performAccessibilityAction(int action, Bundle arguments) {
2680 if (super.performAccessibilityAction(action, arguments)) {
2681 return true;
2682 }
2683 switch (action) {
2684 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2685 if (getCurrentPage() < getPageCount() - 1) {
2686 scrollRight();
2687 return true;
2688 }
2689 } break;
2690 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2691 if (getCurrentPage() > 0) {
2692 scrollLeft();
2693 return true;
2694 }
2695 } break;
2696 }
2697 return false;
2698 }
2699
Adam Cohen0ffac432013-07-10 11:19:26 -07002700 protected String getCurrentPageDescription() {
2701 return String.format(getContext().getString(R.string.default_scroll_format),
2702 getNextPage() + 1, getChildCount());
2703 }
2704
Winson Chungd11265e2011-08-30 13:37:23 -07002705 @Override
2706 public boolean onHoverEvent(android.view.MotionEvent event) {
2707 return true;
2708 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002709}