blob: 30c3ea7528acdc291a527c7058877afc03e49279 [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);
Winson Chungd2be3812013-07-16 11:11:32 -0700344 }
345 }
346
347 protected void onDetachedFromWindow() {
348 // Unhook the page indicator
349 mPageIndicator = null;
350 }
351
Adam Cohen7d30a372013-07-01 17:03:59 -0700352 void setDeleteDropTarget(View v) {
353 mDeleteDropTarget = v;
354 }
355
356 // Convenience methods to map points from self to parent and vice versa
357 float[] mapPointFromViewToParent(View v, float x, float y) {
358 mTmpPoint[0] = x;
359 mTmpPoint[1] = y;
360 v.getMatrix().mapPoints(mTmpPoint);
361 mTmpPoint[0] += v.getLeft();
362 mTmpPoint[1] += v.getTop();
363 return mTmpPoint;
364 }
365 float[] mapPointFromParentToView(View v, float x, float y) {
366 mTmpPoint[0] = x - v.getLeft();
367 mTmpPoint[1] = y - v.getTop();
368 v.getMatrix().invert(mTmpInvMatrix);
369 mTmpInvMatrix.mapPoints(mTmpPoint);
370 return mTmpPoint;
371 }
372
373 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700374 if (mDragView != null) {
375 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
376 (mDragViewBaselineLeft - mDragView.getLeft());
377 float y = mLastMotionY - mDownMotionY;
378 mDragView.setTranslationX(x);
379 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700380
Adam Cohenf358a4b2013-07-23 16:47:31 -0700381 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
382 + x + ", " + y);
383 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700384 }
385
386 public void setMinScale(float f) {
387 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700388 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700389 requestLayout();
390 }
391
392 @Override
393 public void setScaleX(float scaleX) {
394 super.setScaleX(scaleX);
395 if (isReordering(true)) {
396 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
397 mLastMotionX = p[0];
398 mLastMotionY = p[1];
399 updateDragViewTranslationDuringDrag();
400 }
401 }
402
403 // Convenience methods to get the actual width/height of the PagedView (since it is measured
404 // to be larger to account for the minimum possible scale)
405 int getViewportWidth() {
406 return mViewport.width();
407 }
408 int getViewportHeight() {
409 return mViewport.height();
410 }
411
412 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
413 // PagedView both horizontally and vertically
414 int getViewportOffsetX() {
415 return (getMeasuredWidth() - getViewportWidth()) / 2;
416 }
417
418 int getViewportOffsetY() {
419 return (getMeasuredHeight() - getViewportHeight()) / 2;
420 }
421
Adam Cohenedb40762013-07-18 16:45:45 -0700422 PageIndicator getPageIndicator() {
423 return mPageIndicator;
424 }
Winson Chung82dfe582013-07-26 15:07:49 -0700425 protected int getPageIndicatorMarker(int pageIndex) {
426 return R.layout.page_indicator_marker;
427 }
Adam Cohenedb40762013-07-18 16:45:45 -0700428
Winson Chung86f77532010-08-24 11:08:22 -0700429 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
430 mPageSwitchListener = pageSwitchListener;
431 if (mPageSwitchListener != null) {
432 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700433 }
434 }
435
436 /**
Winson Chung52aee602013-01-30 12:01:02 -0800437 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
438 */
439 public boolean isLayoutRtl() {
440 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
441 }
442
443 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700444 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
445 * out pages.
446 */
447 protected void setDataIsReady() {
448 mIsDataReady = true;
449 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700450
Winson Chungf0ea4d32011-06-06 14:27:16 -0700451 protected boolean isDataReady() {
452 return mIsDataReady;
453 }
454
455 /**
Winson Chung86f77532010-08-24 11:08:22 -0700456 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700457 *
Winson Chung86f77532010-08-24 11:08:22 -0700458 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700459 */
Winson Chung86f77532010-08-24 11:08:22 -0700460 int getCurrentPage() {
461 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700462 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700463
Winson Chung360e63f2012-04-27 13:48:05 -0700464 int getNextPage() {
465 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
466 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700467
Winson Chung86f77532010-08-24 11:08:22 -0700468 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700469 return getChildCount();
470 }
471
Winson Chung86f77532010-08-24 11:08:22 -0700472 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700473 return getChildAt(index);
474 }
475
Adam Cohenae4f1552011-10-20 00:15:42 -0700476 protected int indexToPage(int index) {
477 return index;
478 }
479
Winson Chung321e9ee2010-08-09 13:37:56 -0700480 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800481 * Updates the scroll of the current page immediately to its final scroll position. We use this
482 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
483 * the previous tab page.
484 */
485 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700486 // If the current page is invalid, just reset the scroll position to zero
487 int newX = 0;
488 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700489 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700490 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800491 scrollTo(newX, 0);
492 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800493 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800494 }
495
496 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700497 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
498 * ends, {@link #resumeScrolling()} should be called, along with
499 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
500 */
501 void pauseScrolling() {
502 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700503 }
504
505 /**
506 * Enables scrolling again.
507 * @see #pauseScrolling()
508 */
509 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700510 }
511 /**
Winson Chung86f77532010-08-24 11:08:22 -0700512 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700513 */
Winson Chung86f77532010-08-24 11:08:22 -0700514 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800515 if (!mScroller.isFinished()) {
516 mScroller.abortAnimation();
517 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800518 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
519 // the default
520 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800521 return;
522 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700523
Adam Cohene61a9a22013-06-11 15:45:31 -0700524 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700525 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700526 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700527 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800528 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700529 }
530
Winson Chung8c87cd82013-07-23 16:20:10 -0700531 /**
532 * The restore page will be set in place of the current page at the next (likely first)
533 * layout.
534 */
535 void setRestorePage(int restorePage) {
536 mRestorePage = restorePage;
537 }
538
Michael Jurka0142d492010-08-25 17:46:15 -0700539 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700540 if (mPageSwitchListener != null) {
541 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700542 }
Winson Chungd2be3812013-07-16 11:11:32 -0700543
544 // Update the page indicator (when we aren't reordering)
545 if (mPageIndicator != null && !isReordering(false)) {
546 mPageIndicator.setActiveMarker(getNextPage());
547 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700548 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800549 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700550 if (!mIsPageMoving) {
551 mIsPageMoving = true;
552 onPageBeginMoving();
553 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700554 }
555
Michael Jurkace7e05f2011-02-01 22:02:35 -0800556 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700557 if (mIsPageMoving) {
558 mIsPageMoving = false;
559 onPageEndMoving();
560 }
Michael Jurka0142d492010-08-25 17:46:15 -0700561 }
562
Adam Cohen26976d92011-03-22 15:33:33 -0700563 protected boolean isPageMoving() {
564 return mIsPageMoving;
565 }
566
Michael Jurka0142d492010-08-25 17:46:15 -0700567 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700568 protected void onPageBeginMoving() {
569 }
570
571 // a method that subclasses can override to add behavior
572 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700573 }
574
Winson Chung321e9ee2010-08-09 13:37:56 -0700575 /**
Winson Chung86f77532010-08-24 11:08:22 -0700576 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700577 *
578 * @param l The listener used to respond to long clicks.
579 */
580 @Override
581 public void setOnLongClickListener(OnLongClickListener l) {
582 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700583 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700584 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700585 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700586 }
Adam Cohen1697b792013-09-17 19:08:21 -0700587 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700588 }
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
Adam Cohen1697b792013-09-17 19:08:21 -07001594 super.onTouchEvent(ev);
1595
Winson Chung45e1d6e2010-11-09 17:19:49 -08001596 // Skip touch handling if there are no pages to swipe
1597 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1598
Michael Jurkab8f06722010-10-10 15:58:46 -07001599 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001600
1601 final int action = ev.getAction();
1602
1603 switch (action & MotionEvent.ACTION_MASK) {
1604 case MotionEvent.ACTION_DOWN:
1605 /*
1606 * If being flinged and user touches, stop the fling. isFinished
1607 * will be false if being flinged.
1608 */
1609 if (!mScroller.isFinished()) {
1610 mScroller.abortAnimation();
1611 }
1612
1613 // Remember where the motion event started
1614 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001615 mDownMotionY = mLastMotionY = ev.getY();
1616 mDownScrollX = getScrollX();
1617 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1618 mParentDownMotionX = p[0];
1619 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001620 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001621 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001622 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001623
Michael Jurka0142d492010-08-25 17:46:15 -07001624 if (mTouchState == TOUCH_STATE_SCROLLING) {
1625 pageBeginMoving();
1626 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001627 break;
1628
1629 case MotionEvent.ACTION_MOVE:
1630 if (mTouchState == TOUCH_STATE_SCROLLING) {
1631 // Scroll to follow the motion event
1632 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001633
1634 if (pointerIndex == -1) return true;
1635
Winson Chung321e9ee2010-08-09 13:37:56 -07001636 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001637 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001638
Adam Cohenaefd4e12011-02-14 16:39:38 -08001639 mTotalMotionX += Math.abs(deltaX);
1640
Winson Chungc0844aa2011-02-02 15:25:58 -08001641 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1642 // keep the remainder because we are actually testing if we've moved from the last
1643 // scrolled position (which is discrete).
1644 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001645 mTouchX += deltaX;
1646 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1647 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001648 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001649 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001650 } else {
1651 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001652 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001653 mLastMotionX = x;
1654 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001655 } else {
1656 awakenScrollBars();
1657 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001658 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1659 // Update the last motion position
1660 mLastMotionX = ev.getX();
1661 mLastMotionY = ev.getY();
1662
1663 // Update the parent down so that our zoom animations take this new movement into
1664 // account
1665 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1666 mParentDownMotionX = pt[0];
1667 mParentDownMotionY = pt[1];
1668 updateDragViewTranslationDuringDrag();
1669
1670 // Find the closest page to the touch point
1671 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001672
1673 // Change the drag view if we are hovering over the drop target
1674 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1675 (int) mParentDownMotionX, (int) mParentDownMotionY);
1676 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1677
Adam Cohen7d30a372013-07-01 17:03:59 -07001678 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1679 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1680 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1681 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1682
Adam Cohenf358a4b2013-07-23 16:47:31 -07001683 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1684 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1685 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001686 mTempVisiblePagesRange[0] = 0;
1687 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001688 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001689 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1690 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1691 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1692 mSidePageHoverIndex = pageUnderPointIndex;
1693 mSidePageHoverRunnable = new Runnable() {
1694 @Override
1695 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001696 // Setup the scroll to the correct page before we swap the views
1697 snapToPage(pageUnderPointIndex);
1698
1699 // For each of the pages between the paged view and the drag view,
1700 // animate them from the previous position to the new position in
1701 // the layout (as a result of the drag view moving in the layout)
1702 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1703 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1704 dragViewIndex + 1 : pageUnderPointIndex;
1705 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1706 dragViewIndex - 1 : pageUnderPointIndex;
1707 for (int i = lowerIndex; i <= upperIndex; ++i) {
1708 View v = getChildAt(i);
1709 // dragViewIndex < pageUnderPointIndex, so after we remove the
1710 // drag view all subsequent views to pageUnderPointIndex will
1711 // shift down.
1712 int oldX = getViewportOffsetX() + getChildOffset(i);
1713 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1714
1715 // Animate the view translation from its old position to its new
1716 // position
1717 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1718 if (anim != null) {
1719 anim.cancel();
1720 }
1721
1722 v.setTranslationX(oldX - newX);
1723 anim = new AnimatorSet();
1724 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1725 anim.playTogether(
1726 ObjectAnimator.ofFloat(v, "translationX", 0f));
1727 anim.start();
1728 v.setTag(anim);
1729 }
1730
1731 removeView(mDragView);
1732 onRemoveView(mDragView, false);
1733 addView(mDragView, pageUnderPointIndex);
1734 onAddView(mDragView, pageUnderPointIndex);
1735 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001736 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001737 }
1738 };
1739 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1740 }
1741 } else {
1742 removeCallbacks(mSidePageHoverRunnable);
1743 mSidePageHoverIndex = -1;
1744 }
Adam Cohen564976a2010-10-13 18:52:07 -07001745 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001746 determineScrollingStart(ev);
1747 }
1748 break;
1749
1750 case MotionEvent.ACTION_UP:
1751 if (mTouchState == TOUCH_STATE_SCROLLING) {
1752 final int activePointerId = mActivePointerId;
1753 final int pointerIndex = ev.findPointerIndex(activePointerId);
1754 final float x = ev.getX(pointerIndex);
1755 final VelocityTracker velocityTracker = mVelocityTracker;
1756 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1757 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001758 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001759 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001760 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1761 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001762
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001763 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1764
Adam Cohen00481b32011-11-18 12:03:48 -08001765 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001766 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001767
Adam Cohenf358a4b2013-07-23 16:47:31 -07001768 if (!mFreeScroll) {
1769 // In the case that the page is moved far to one direction and then is flung
1770 // in the opposite direction, we use a threshold to determine whether we should
1771 // just return to the starting page, or if we should skip one further.
1772 boolean returnToOriginalPage = false;
1773 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1774 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1775 returnToOriginalPage = true;
1776 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001777
Adam Cohenf358a4b2013-07-23 16:47:31 -07001778 int finalPage;
1779 // We give flings precedence over large moves, which is why we short-circuit our
1780 // test for a large move if a fling has been registered. That is, a large
1781 // move to the left and fling to the right will register as a fling to the right.
1782 final boolean isRtl = isLayoutRtl();
1783 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1784 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1785 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1786 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1787 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1788 snapToPageWithVelocity(finalPage, velocityX);
1789 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1790 (isFling && isVelocityXLeft)) &&
1791 mCurrentPage < getChildCount() - 1) {
1792 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1793 snapToPageWithVelocity(finalPage, velocityX);
1794 } else {
1795 snapToDestination();
1796 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1797 // at this point we have not moved beyond the touch slop
1798 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1799 // we can just page
1800 int nextPage = Math.max(0, mCurrentPage - 1);
1801 if (nextPage != mCurrentPage) {
1802 snapToPage(nextPage);
1803 } else {
1804 snapToDestination();
1805 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001806 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001807 if (!mScroller.isFinished()) {
1808 mScroller.abortAnimation();
1809 }
1810
1811 float scaleX = getScaleX();
1812 int vX = (int) (-velocityX * scaleX);
1813 int initialScrollX = (int) (getScrollX() * scaleX);
1814
1815 mScroller.fling(initialScrollX,
1816 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1817 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001818 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001819 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001820 // at this point we have not moved beyond the touch slop
1821 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1822 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001823 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1824 if (nextPage != mCurrentPage) {
1825 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001826 } else {
1827 snapToDestination();
1828 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001829 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1830 // Update the last motion position
1831 mLastMotionX = ev.getX();
1832 mLastMotionY = ev.getY();
1833
1834 // Update the parent down so that our zoom animations take this new movement into
1835 // account
1836 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1837 mParentDownMotionX = pt[0];
1838 mParentDownMotionY = pt[1];
1839 updateDragViewTranslationDuringDrag();
1840 boolean handledFling = false;
1841 if (!DISABLE_FLING_TO_DELETE) {
1842 // Check the velocity and see if we are flinging-to-delete
1843 PointF flingToDeleteVector = isFlingingToDelete();
1844 if (flingToDeleteVector != null) {
1845 onFlingToDelete(flingToDeleteVector);
1846 handledFling = true;
1847 }
1848 }
1849 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1850 (int) mParentDownMotionY)) {
1851 onDropToDelete();
1852 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001853 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001854 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001855 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001856
1857 // Remove the callback to wait for the side page hover timeout
1858 removeCallbacks(mSidePageHoverRunnable);
1859 // End any intermediate reordering states
1860 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001861 break;
1862
1863 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001864 if (mTouchState == TOUCH_STATE_SCROLLING) {
1865 snapToDestination();
1866 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001867 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001868 break;
1869
1870 case MotionEvent.ACTION_POINTER_UP:
1871 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001872 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001873 break;
1874 }
1875
1876 return true;
1877 }
1878
Adam Cohen7d30a372013-07-01 17:03:59 -07001879 public void onFlingToDelete(View v) {}
1880 public void onRemoveView(View v, boolean deletePermanently) {}
1881 public void onRemoveViewAnimationCompleted() {}
1882 public void onAddView(View v, int index) {}
1883
1884 private void resetTouchState() {
1885 releaseVelocityTracker();
1886 endReordering();
1887 mTouchState = TOUCH_STATE_REST;
1888 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001889 }
1890
Adam Cohen1697b792013-09-17 19:08:21 -07001891 protected void onUnhandledTap(MotionEvent ev) {
1892 ((Launcher) getContext()).onClick(this);
1893 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001894
Winson Chung185d7162011-02-28 13:47:29 -08001895 @Override
1896 public boolean onGenericMotionEvent(MotionEvent event) {
1897 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1898 switch (event.getAction()) {
1899 case MotionEvent.ACTION_SCROLL: {
1900 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1901 final float vscroll;
1902 final float hscroll;
1903 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1904 vscroll = 0;
1905 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1906 } else {
1907 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1908 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1909 }
1910 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001911 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1912 : (hscroll > 0 || vscroll > 0);
1913 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001914 scrollRight();
1915 } else {
1916 scrollLeft();
1917 }
1918 return true;
1919 }
1920 }
1921 }
1922 }
1923 return super.onGenericMotionEvent(event);
1924 }
1925
Michael Jurkab8f06722010-10-10 15:58:46 -07001926 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1927 if (mVelocityTracker == null) {
1928 mVelocityTracker = VelocityTracker.obtain();
1929 }
1930 mVelocityTracker.addMovement(ev);
1931 }
1932
1933 private void releaseVelocityTracker() {
1934 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001935 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001936 mVelocityTracker.recycle();
1937 mVelocityTracker = null;
1938 }
1939 }
1940
Winson Chung321e9ee2010-08-09 13:37:56 -07001941 private void onSecondaryPointerUp(MotionEvent ev) {
1942 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1943 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1944 final int pointerId = ev.getPointerId(pointerIndex);
1945 if (pointerId == mActivePointerId) {
1946 // This was our active pointer going up. Choose a new
1947 // active pointer and adjust accordingly.
1948 // TODO: Make this decision more intelligent.
1949 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1950 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1951 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001952 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001953 mActivePointerId = ev.getPointerId(newPointerIndex);
1954 if (mVelocityTracker != null) {
1955 mVelocityTracker.clear();
1956 }
1957 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001958 }
1959
Winson Chung321e9ee2010-08-09 13:37:56 -07001960 @Override
1961 public void requestChildFocus(View child, View focused) {
1962 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001963 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001964 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001965 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001966 }
1967 }
1968
Winson Chung1908d072011-02-24 18:09:44 -08001969 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001970 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001971 }
1972
Adam Cohen7d30a372013-07-01 17:03:59 -07001973 int getPageNearestToPoint(float x) {
1974 int index = 0;
1975 for (int i = 0; i < getChildCount(); ++i) {
1976 if (x < getChildAt(i).getRight() - getScrollX()) {
1977 return index;
1978 } else {
1979 index++;
1980 }
1981 }
1982 return Math.min(index, getChildCount() - 1);
1983 }
1984
Adam Cohend19d3ca2010-09-15 14:43:42 -07001985 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001986 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001987 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001988 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001989 final int childCount = getChildCount();
1990 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001991 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001992 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001993 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001994 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001995 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1996 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1997 minDistanceFromScreenCenter = distanceFromScreenCenter;
1998 minDistanceFromScreenCenterIndex = i;
1999 }
2000 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002001 return minDistanceFromScreenCenterIndex;
2002 }
2003
2004 protected void snapToDestination() {
2005 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002006 }
2007
Adam Cohene0f66b52010-11-23 15:06:07 -08002008 private static class ScrollInterpolator implements Interpolator {
2009 public ScrollInterpolator() {
2010 }
2011
2012 public float getInterpolation(float t) {
2013 t -= 1.0f;
2014 return t*t*t*t*t + 1;
2015 }
2016 }
2017
2018 // We want the duration of the page snap animation to be influenced by the distance that
2019 // the screen has to travel, however, we don't want this duration to be effected in a
2020 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2021 // of travel has on the overall snap duration.
2022 float distanceInfluenceForSnapDuration(float f) {
2023 f -= 0.5f; // center the values about 0.
2024 f *= 0.3f * Math.PI / 2.0f;
2025 return (float) Math.sin(f);
2026 }
2027
Michael Jurka0142d492010-08-25 17:46:15 -07002028 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002029 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002030 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002031
Adam Cohenedb40762013-07-18 16:45:45 -07002032 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002033 int delta = newX - mUnboundedScrollX;
2034 int duration = 0;
2035
Adam Cohen265b9a62011-12-07 14:37:18 -08002036 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002037 // If the velocity is low enough, then treat this more as an automatic page advance
2038 // as opposed to an apparent physical response to flinging
2039 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2040 return;
2041 }
2042
2043 // Here we compute a "distance" that will be used in the computation of the overall
2044 // snap duration. This is a function of the actual distance that needs to be traveled;
2045 // we keep this value close to half screen size in order to reduce the variance in snap
2046 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002047 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002048 float distance = halfScreenSize + halfScreenSize *
2049 distanceInfluenceForSnapDuration(distanceRatio);
2050
2051 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002052 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002053
2054 // we want the page's snap velocity to approximately match the velocity at which the
2055 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002056 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2057 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002058
2059 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002060 }
2061
2062 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002063 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002064 }
2065
Adam Cohen7d30a372013-07-01 17:03:59 -07002066 protected void snapToPageImmediately(int whichPage) {
2067 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2068 }
2069
Michael Jurka0142d492010-08-25 17:46:15 -07002070 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002071 snapToPage(whichPage, duration, false);
2072 }
2073
2074 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002075 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002076
Adam Cohenedb40762013-07-18 16:45:45 -07002077 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002078 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002079 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002080 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002081 }
2082
2083 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002084 snapToPage(whichPage, delta, duration, false);
2085 }
Michael Jurka0142d492010-08-25 17:46:15 -07002086
Adam Cohen7d30a372013-07-01 17:03:59 -07002087 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2088 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002089 View focusedChild = getFocusedChild();
2090 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002091 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002092 focusedChild.clearFocus();
2093 }
2094
2095 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002096 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002097 if (immediate) {
2098 duration = 0;
2099 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002100 duration = Math.abs(delta);
2101 }
2102
Adam Cohenf358a4b2013-07-23 16:47:31 -07002103 if (!mScroller.isFinished()) {
2104 mScroller.abortAnimation();
2105 }
Adam Cohen68d73932010-11-15 10:50:58 -08002106 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002107
Michael Jurka0142d492010-08-25 17:46:15 -07002108 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002109
2110 // Trigger a compute() to finish switching pages if necessary
2111 if (immediate) {
2112 computeScroll();
2113 }
2114
Winson Chung9c0565f2013-07-19 13:49:06 -07002115 // Defer loading associated pages until the scroll settles
2116 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2117
Adam Cohen7d30a372013-07-01 17:03:59 -07002118 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002119 invalidate();
2120 }
2121
Winson Chung321e9ee2010-08-09 13:37:56 -07002122 public void scrollLeft() {
2123 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002124 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002125 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002126 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002127 }
2128 }
2129
2130 public void scrollRight() {
2131 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002132 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002133 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002134 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002135 }
2136 }
2137
Winson Chung86f77532010-08-24 11:08:22 -07002138 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002139 int result = -1;
2140 if (v != null) {
2141 ViewParent vp = v.getParent();
2142 int count = getChildCount();
2143 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002144 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002145 return i;
2146 }
2147 }
2148 }
2149 return result;
2150 }
2151
2152 /**
2153 * @return True is long presses are still allowed for the current touch
2154 */
2155 public boolean allowLongPress() {
2156 return mAllowLongPress;
2157 }
2158
Michael Jurka0142d492010-08-25 17:46:15 -07002159 /**
2160 * Set true to allow long-press events to be triggered, usually checked by
2161 * {@link Launcher} to accept or block dpad-initiated long-presses.
2162 */
2163 public void setAllowLongPress(boolean allowLongPress) {
2164 mAllowLongPress = allowLongPress;
2165 }
2166
Winson Chung321e9ee2010-08-09 13:37:56 -07002167 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002168 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002169
2170 SavedState(Parcelable superState) {
2171 super(superState);
2172 }
2173
2174 private SavedState(Parcel in) {
2175 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002176 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002177 }
2178
2179 @Override
2180 public void writeToParcel(Parcel out, int flags) {
2181 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002182 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002183 }
2184
2185 public static final Parcelable.Creator<SavedState> CREATOR =
2186 new Parcelable.Creator<SavedState>() {
2187 public SavedState createFromParcel(Parcel in) {
2188 return new SavedState(in);
2189 }
2190
2191 public SavedState[] newArray(int size) {
2192 return new SavedState[size];
2193 }
2194 };
2195 }
2196
Winson Chungf314b0e2011-08-16 11:54:27 -07002197 protected void loadAssociatedPages(int page) {
2198 loadAssociatedPages(page, false);
2199 }
2200 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002201 if (mContentIsRefreshable) {
2202 final int count = getChildCount();
2203 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002204 int lowerPageBound = getAssociatedLowerPageBound(page);
2205 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002206 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2207 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002208 // First, clear any pages that should no longer be loaded
2209 for (int i = 0; i < count; ++i) {
2210 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002211 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002212 if (layout.getPageChildCount() > 0) {
2213 layout.removeAllViewsOnPage();
2214 }
2215 mDirtyPageContent.set(i, true);
2216 }
2217 }
2218 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002219 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002220 if ((i != page) && immediateAndOnly) {
2221 continue;
2222 }
Michael Jurka0142d492010-08-25 17:46:15 -07002223 if (lowerPageBound <= i && i <= upperPageBound) {
2224 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002225 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002226 mDirtyPageContent.set(i, false);
2227 }
Winson Chung86f77532010-08-24 11:08:22 -07002228 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002229 }
2230 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002231 }
2232 }
2233
Winson Chunge3193b92010-09-10 11:44:42 -07002234 protected int getAssociatedLowerPageBound(int page) {
2235 return Math.max(0, page - 1);
2236 }
2237 protected int getAssociatedUpperPageBound(int page) {
2238 final int count = getChildCount();
2239 return Math.min(page + 1, count - 1);
2240 }
2241
Winson Chung86f77532010-08-24 11:08:22 -07002242 /**
2243 * This method is called ONLY to synchronize the number of pages that the paged view has.
2244 * To actually fill the pages with information, implement syncPageItems() below. It is
2245 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2246 * and therefore, individual page items do not need to be updated in this method.
2247 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002248 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002249
2250 /**
2251 * This method is called to synchronize the items that are on a particular page. If views on
2252 * the page can be reused, then they should be updated within this method.
2253 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002254 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002255
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002256 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002257 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002258 }
2259 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002260 invalidatePageData(currentPage, false);
2261 }
2262 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002263 if (!mIsDataReady) {
2264 return;
2265 }
2266
Michael Jurka0142d492010-08-25 17:46:15 -07002267 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002268 // Force all scrolling-related behavior to end
2269 mScroller.forceFinished(true);
2270 mNextPage = INVALID_PAGE;
2271
Michael Jurka0142d492010-08-25 17:46:15 -07002272 // Update all the pages
2273 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002274
Winson Chung5a808352011-06-27 19:08:49 -07002275 // We must force a measure after we've loaded the pages to update the content width and
2276 // to determine the full scroll width
2277 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2278 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2279
2280 // Set a new page as the current page if necessary
2281 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002282 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002283 }
2284
Michael Jurka0142d492010-08-25 17:46:15 -07002285 // Mark each of the pages as dirty
2286 final int count = getChildCount();
2287 mDirtyPageContent.clear();
2288 for (int i = 0; i < count; ++i) {
2289 mDirtyPageContent.add(true);
2290 }
2291
2292 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002293 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002294 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002295 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002296 }
Winson Chung007c6982011-06-14 13:27:53 -07002297
Adam Cohen7d30a372013-07-01 17:03:59 -07002298 // Animate the drag view back to the original position
2299 void animateDragViewToOriginalPosition() {
2300 if (mDragView != null) {
2301 AnimatorSet anim = new AnimatorSet();
2302 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2303 anim.playTogether(
2304 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002305 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2306 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2307 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002308 anim.addListener(new AnimatorListenerAdapter() {
2309 @Override
2310 public void onAnimationEnd(Animator animation) {
2311 onPostReorderingAnimationCompleted();
2312 }
2313 });
2314 anim.start();
2315 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002316 }
2317
Adam Cohen7d30a372013-07-01 17:03:59 -07002318 protected void onStartReordering() {
2319 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2320 mTouchState = TOUCH_STATE_REORDERING;
2321 mIsReordering = true;
2322
Adam Cohen7d30a372013-07-01 17:03:59 -07002323 // We must invalidate to trigger a redraw to update the layers such that the drag view
2324 // is always drawn on top
2325 invalidate();
2326 }
2327
2328 private void onPostReorderingAnimationCompleted() {
2329 // Trigger the callback when reordering has settled
2330 --mPostReorderingPreZoomInRemainingAnimationCount;
2331 if (mPostReorderingPreZoomInRunnable != null &&
2332 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2333 mPostReorderingPreZoomInRunnable.run();
2334 mPostReorderingPreZoomInRunnable = null;
2335 }
2336 }
2337
2338 protected void onEndReordering() {
2339 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002340 }
2341
Adam Cohenf358a4b2013-07-23 16:47:31 -07002342 public boolean startReordering(View v) {
2343 int dragViewIndex = indexOfChild(v);//getPageNearestToCenterOfScreen();
Adam Cohen7d30a372013-07-01 17:03:59 -07002344 mTempVisiblePagesRange[0] = 0;
2345 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002346 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002347 mReorderingStarted = true;
2348
2349 // Check if we are within the reordering range
2350 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002351 dragViewIndex <= mTempVisiblePagesRange[1]) {
2352 // Find the drag view under the pointer
2353 mDragView = getChildAt(dragViewIndex);
2354 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2355 mDragViewBaselineLeft = mDragView.getLeft();
2356 disableFreeScroll(-1);
2357 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002358 return true;
2359 }
2360 return false;
2361 }
2362
2363 boolean isReordering(boolean testTouchState) {
2364 boolean state = mIsReordering;
2365 if (testTouchState) {
2366 state &= (mTouchState == TOUCH_STATE_REORDERING);
2367 }
2368 return state;
2369 }
2370 void endReordering() {
2371 // For simplicity, we call endReordering sometimes even if reordering was never started.
2372 // In that case, we don't want to do anything.
2373 if (!mReorderingStarted) return;
2374 mReorderingStarted = false;
2375
2376 // If we haven't flung-to-delete the current child, then we just animate the drag view
2377 // back into position
2378 final Runnable onCompleteRunnable = new Runnable() {
2379 @Override
2380 public void run() {
2381 onEndReordering();
2382 }
2383 };
2384 if (!mDeferringForDelete) {
2385 mPostReorderingPreZoomInRunnable = new Runnable() {
2386 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002387 onCompleteRunnable.run();
2388 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002389 };
2390 };
2391
2392 mPostReorderingPreZoomInRemainingAnimationCount =
2393 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2394 // Snap to the current page
2395 snapToPage(indexOfChild(mDragView), 0);
2396 // Animate the drag view back to the front position
2397 animateDragViewToOriginalPosition();
2398 } else {
2399 // Handled in post-delete-animation-callbacks
2400 }
2401 }
2402
Adam Cohen7d30a372013-07-01 17:03:59 -07002403 /*
2404 * Flinging to delete - IN PROGRESS
2405 */
2406 private PointF isFlingingToDelete() {
2407 ViewConfiguration config = ViewConfiguration.get(getContext());
2408 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2409
2410 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2411 // Do a quick dot product test to ensure that we are flinging upwards
2412 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2413 mVelocityTracker.getYVelocity());
2414 PointF upVec = new PointF(0f, -1f);
2415 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2416 (vel.length() * upVec.length()));
2417 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2418 return vel;
2419 }
2420 }
2421 return null;
2422 }
2423
2424 /**
2425 * Creates an animation from the current drag view along its current velocity vector.
2426 * For this animation, the alpha runs for a fixed duration and we update the position
2427 * progressively.
2428 */
2429 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2430 private View mDragView;
2431 private PointF mVelocity;
2432 private Rect mFrom;
2433 private long mPrevTime;
2434 private float mFriction;
2435
2436 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2437
2438 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2439 long startTime, float friction) {
2440 mDragView = dragView;
2441 mVelocity = vel;
2442 mFrom = from;
2443 mPrevTime = startTime;
2444 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2445 }
2446
2447 @Override
2448 public void onAnimationUpdate(ValueAnimator animation) {
2449 float t = ((Float) animation.getAnimatedValue()).floatValue();
2450 long curTime = AnimationUtils.currentAnimationTimeMillis();
2451
2452 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2453 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2454
2455 mDragView.setTranslationX(mFrom.left);
2456 mDragView.setTranslationY(mFrom.top);
2457 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2458
2459 mVelocity.x *= mFriction;
2460 mVelocity.y *= mFriction;
2461 mPrevTime = curTime;
2462 }
2463 };
2464
2465 private static final int ANIM_TAG_KEY = 100;
2466
2467 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2468 return new Runnable() {
2469 @Override
2470 public void run() {
2471 int dragViewIndex = indexOfChild(dragView);
2472
2473 // For each of the pages around the drag view, animate them from the previous
2474 // position to the new position in the layout (as a result of the drag view moving
2475 // in the layout)
2476 // NOTE: We can make an assumption here because we have side-bound pages that we
2477 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002478 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002479 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2480 boolean slideFromLeft = (isLastWidgetPage ||
2481 dragViewIndex > mTempVisiblePagesRange[0]);
2482
2483 // Setup the scroll to the correct page before we swap the views
2484 if (slideFromLeft) {
2485 snapToPageImmediately(dragViewIndex - 1);
2486 }
2487
2488 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2489 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2490 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2491 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2492 ArrayList<Animator> animations = new ArrayList<Animator>();
2493 for (int i = lowerIndex; i <= upperIndex; ++i) {
2494 View v = getChildAt(i);
2495 // dragViewIndex < pageUnderPointIndex, so after we remove the
2496 // drag view all subsequent views to pageUnderPointIndex will
2497 // shift down.
2498 int oldX = 0;
2499 int newX = 0;
2500 if (slideFromLeft) {
2501 if (i == 0) {
2502 // Simulate the page being offscreen with the page spacing
2503 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2504 - mPageSpacing;
2505 } else {
2506 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2507 }
2508 newX = getViewportOffsetX() + getChildOffset(i);
2509 } else {
2510 oldX = getChildOffset(i) - getChildOffset(i - 1);
2511 newX = 0;
2512 }
2513
2514 // Animate the view translation from its old position to its new
2515 // position
2516 AnimatorSet anim = (AnimatorSet) v.getTag();
2517 if (anim != null) {
2518 anim.cancel();
2519 }
2520
2521 // Note: Hacky, but we want to skip any optimizations to not draw completely
2522 // hidden views
2523 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2524 v.setTranslationX(oldX - newX);
2525 anim = new AnimatorSet();
2526 anim.playTogether(
2527 ObjectAnimator.ofFloat(v, "translationX", 0f),
2528 ObjectAnimator.ofFloat(v, "alpha", 1f));
2529 animations.add(anim);
2530 v.setTag(ANIM_TAG_KEY, anim);
2531 }
2532
2533 AnimatorSet slideAnimations = new AnimatorSet();
2534 slideAnimations.playTogether(animations);
2535 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2536 slideAnimations.addListener(new AnimatorListenerAdapter() {
2537 @Override
2538 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002539 mDeferringForDelete = false;
2540 onEndReordering();
2541 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002542 }
2543 });
2544 slideAnimations.start();
2545
2546 removeView(dragView);
2547 onRemoveView(dragView, true);
2548 }
2549 };
2550 }
2551
2552 public void onFlingToDelete(PointF vel) {
2553 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2554
2555 // NOTE: Because it takes time for the first frame of animation to actually be
2556 // called and we expect the animation to be a continuation of the fling, we have
2557 // to account for the time that has elapsed since the fling finished. And since
2558 // we don't have a startDelay, we will always get call to update when we call
2559 // start() (which we want to ignore).
2560 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2561 private int mCount = -1;
2562 private long mStartTime;
2563 private float mOffset;
2564 /* Anonymous inner class ctor */ {
2565 mStartTime = startTime;
2566 }
2567
2568 @Override
2569 public float getInterpolation(float t) {
2570 if (mCount < 0) {
2571 mCount++;
2572 } else if (mCount == 0) {
2573 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2574 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2575 mCount++;
2576 }
2577 return Math.min(1f, mOffset + t);
2578 }
2579 };
2580
2581 final Rect from = new Rect();
2582 final View dragView = mDragView;
2583 from.left = (int) dragView.getTranslationX();
2584 from.top = (int) dragView.getTranslationY();
2585 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2586 from, startTime, FLING_TO_DELETE_FRICTION);
2587
2588 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2589
2590 // Create and start the animation
2591 ValueAnimator mDropAnim = new ValueAnimator();
2592 mDropAnim.setInterpolator(tInterpolator);
2593 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2594 mDropAnim.setFloatValues(0f, 1f);
2595 mDropAnim.addUpdateListener(updateCb);
2596 mDropAnim.addListener(new AnimatorListenerAdapter() {
2597 public void onAnimationEnd(Animator animation) {
2598 onAnimationEndRunnable.run();
2599 }
2600 });
2601 mDropAnim.start();
2602 mDeferringForDelete = true;
2603 }
2604
2605 /* Drag to delete */
2606 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2607 if (mDeleteDropTarget != null) {
2608 mAltTmpRect.set(0, 0, 0, 0);
2609 View parent = (View) mDeleteDropTarget.getParent();
2610 if (parent != null) {
2611 parent.getGlobalVisibleRect(mAltTmpRect);
2612 }
2613 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2614 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2615 return mTmpRect.contains(x, y);
2616 }
2617 return false;
2618 }
2619
2620 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2621
2622 private void onDropToDelete() {
2623 final View dragView = mDragView;
2624
2625 final float toScale = 0f;
2626 final float toAlpha = 0f;
2627
2628 // Create and start the complex animation
2629 ArrayList<Animator> animations = new ArrayList<Animator>();
2630 AnimatorSet motionAnim = new AnimatorSet();
2631 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2632 motionAnim.playTogether(
2633 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2634 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2635 animations.add(motionAnim);
2636
2637 AnimatorSet alphaAnim = new AnimatorSet();
2638 alphaAnim.setInterpolator(new LinearInterpolator());
2639 alphaAnim.playTogether(
2640 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2641 animations.add(alphaAnim);
2642
2643 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2644
2645 AnimatorSet anim = new AnimatorSet();
2646 anim.playTogether(animations);
2647 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2648 anim.addListener(new AnimatorListenerAdapter() {
2649 public void onAnimationEnd(Animator animation) {
2650 onAnimationEndRunnable.run();
2651 }
2652 });
2653 anim.start();
2654
2655 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002656 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002657
2658 /* Accessibility */
2659 @Override
2660 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2661 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002662 info.setScrollable(getPageCount() > 1);
2663 if (getCurrentPage() < getPageCount() - 1) {
2664 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2665 }
2666 if (getCurrentPage() > 0) {
2667 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2668 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002669 }
2670
2671 @Override
2672 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2673 super.onInitializeAccessibilityEvent(event);
2674 event.setScrollable(true);
2675 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2676 event.setFromIndex(mCurrentPage);
2677 event.setToIndex(mCurrentPage);
2678 event.setItemCount(getChildCount());
2679 }
2680 }
2681
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002682 @Override
2683 public boolean performAccessibilityAction(int action, Bundle arguments) {
2684 if (super.performAccessibilityAction(action, arguments)) {
2685 return true;
2686 }
2687 switch (action) {
2688 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2689 if (getCurrentPage() < getPageCount() - 1) {
2690 scrollRight();
2691 return true;
2692 }
2693 } break;
2694 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2695 if (getCurrentPage() > 0) {
2696 scrollLeft();
2697 return true;
2698 }
2699 } break;
2700 }
2701 return false;
2702 }
2703
Adam Cohen0ffac432013-07-10 11:19:26 -07002704 protected String getCurrentPageDescription() {
2705 return String.format(getContext().getString(R.string.default_scroll_format),
2706 getNextPage() + 1, getChildCount());
2707 }
2708
Winson Chungd11265e2011-08-30 13:37:23 -07002709 @Override
2710 public boolean onHoverEvent(android.view.MotionEvent event) {
2711 return true;
2712 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002713}