blob: 76c9a320526f35c385e888570156ead19debf902 [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
Winson Chung86f77532010-08-24 11:08:22 -0700263 public interface PageSwitchListener {
264 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700265 }
266
Winson Chung321e9ee2010-08-09 13:37:56 -0700267 public PagedView(Context context) {
268 this(context, null);
269 }
270
271 public PagedView(Context context, AttributeSet attrs) {
272 this(context, attrs, 0);
273 }
274
275 public PagedView(Context context, AttributeSet attrs, int defStyle) {
276 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700277
Adam Cohen9c4949e2010-10-05 12:27:22 -0700278 TypedArray a = context.obtainStyledAttributes(attrs,
279 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800280 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700281 if (mPageSpacing < 0) {
282 mAutoComputePageSpacing = mRecomputePageSpacing = true;
283 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700284 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800285 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700286 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800287 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700288 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800289 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700290 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800291 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700292 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700293 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700294 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700295 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700296 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700297 a.recycle();
298
Winson Chung321e9ee2010-08-09 13:37:56 -0700299 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700300 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700301 }
302
303 /**
304 * Initializes various states for this workspace.
305 */
Michael Jurka0142d492010-08-25 17:46:15 -0700306 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700307 mDirtyPageContent = new ArrayList<Boolean>();
308 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800309 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700310 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700311 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700312
313 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700314 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700315 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
316 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700317 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800318
Adam Cohen7d30a372013-07-01 17:03:59 -0700319 // Scale the fling-to-delete threshold by the density
320 mFlingToDeleteThresholdVelocity =
321 (int) (mFlingToDeleteThresholdVelocity * mDensity);
322
Adam Cohen265b9a62011-12-07 14:37:18 -0800323 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
324 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
325 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700326 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700327 }
328
Winson Chungd2be3812013-07-16 11:11:32 -0700329 protected void onAttachedToWindow() {
330 // Hook up the page indicator
331 ViewGroup parent = (ViewGroup) getParent();
332 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
333 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700334 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700335
336 ArrayList<Integer> markers = new ArrayList<Integer>();
337 for (int i = 0; i < getChildCount(); ++i) {
338 markers.add(getPageIndicatorMarker(i));
339 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700340
Winson Chungc58497e2013-09-03 17:48:37 -0700341 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Adam Cohenf358a4b2013-07-23 16:47:31 -0700342 mPageIndicator.setOnClickListener((Launcher) getContext());
Winson Chungd2be3812013-07-16 11:11:32 -0700343 }
344 }
345
346 protected void onDetachedFromWindow() {
347 // Unhook the page indicator
348 mPageIndicator = null;
349 }
350
Adam Cohen7d30a372013-07-01 17:03:59 -0700351 void setDeleteDropTarget(View v) {
352 mDeleteDropTarget = v;
353 }
354
355 // Convenience methods to map points from self to parent and vice versa
356 float[] mapPointFromViewToParent(View v, float x, float y) {
357 mTmpPoint[0] = x;
358 mTmpPoint[1] = y;
359 v.getMatrix().mapPoints(mTmpPoint);
360 mTmpPoint[0] += v.getLeft();
361 mTmpPoint[1] += v.getTop();
362 return mTmpPoint;
363 }
364 float[] mapPointFromParentToView(View v, float x, float y) {
365 mTmpPoint[0] = x - v.getLeft();
366 mTmpPoint[1] = y - v.getTop();
367 v.getMatrix().invert(mTmpInvMatrix);
368 mTmpInvMatrix.mapPoints(mTmpPoint);
369 return mTmpPoint;
370 }
371
372 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700373 if (mDragView != null) {
374 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
375 (mDragViewBaselineLeft - mDragView.getLeft());
376 float y = mLastMotionY - mDownMotionY;
377 mDragView.setTranslationX(x);
378 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700379
Adam Cohenf358a4b2013-07-23 16:47:31 -0700380 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
381 + x + ", " + y);
382 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700383 }
384
385 public void setMinScale(float f) {
386 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700387 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700388 requestLayout();
389 }
390
391 @Override
392 public void setScaleX(float scaleX) {
393 super.setScaleX(scaleX);
394 if (isReordering(true)) {
395 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
396 mLastMotionX = p[0];
397 mLastMotionY = p[1];
398 updateDragViewTranslationDuringDrag();
399 }
400 }
401
402 // Convenience methods to get the actual width/height of the PagedView (since it is measured
403 // to be larger to account for the minimum possible scale)
404 int getViewportWidth() {
405 return mViewport.width();
406 }
407 int getViewportHeight() {
408 return mViewport.height();
409 }
410
411 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
412 // PagedView both horizontally and vertically
413 int getViewportOffsetX() {
414 return (getMeasuredWidth() - getViewportWidth()) / 2;
415 }
416
417 int getViewportOffsetY() {
418 return (getMeasuredHeight() - getViewportHeight()) / 2;
419 }
420
Adam Cohenedb40762013-07-18 16:45:45 -0700421 PageIndicator getPageIndicator() {
422 return mPageIndicator;
423 }
Winson Chung82dfe582013-07-26 15:07:49 -0700424 protected int getPageIndicatorMarker(int pageIndex) {
425 return R.layout.page_indicator_marker;
426 }
Adam Cohenedb40762013-07-18 16:45:45 -0700427
Winson Chung86f77532010-08-24 11:08:22 -0700428 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
429 mPageSwitchListener = pageSwitchListener;
430 if (mPageSwitchListener != null) {
431 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700432 }
433 }
434
435 /**
Winson Chung52aee602013-01-30 12:01:02 -0800436 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
437 */
438 public boolean isLayoutRtl() {
439 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
440 }
441
442 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700443 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
444 * out pages.
445 */
446 protected void setDataIsReady() {
447 mIsDataReady = true;
448 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700449
Winson Chungf0ea4d32011-06-06 14:27:16 -0700450 protected boolean isDataReady() {
451 return mIsDataReady;
452 }
453
454 /**
Winson Chung86f77532010-08-24 11:08:22 -0700455 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700456 *
Winson Chung86f77532010-08-24 11:08:22 -0700457 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700458 */
Winson Chung86f77532010-08-24 11:08:22 -0700459 int getCurrentPage() {
460 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700461 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700462
Winson Chung360e63f2012-04-27 13:48:05 -0700463 int getNextPage() {
464 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
465 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700466
Winson Chung86f77532010-08-24 11:08:22 -0700467 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700468 return getChildCount();
469 }
470
Winson Chung86f77532010-08-24 11:08:22 -0700471 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700472 return getChildAt(index);
473 }
474
Adam Cohenae4f1552011-10-20 00:15:42 -0700475 protected int indexToPage(int index) {
476 return index;
477 }
478
Winson Chung321e9ee2010-08-09 13:37:56 -0700479 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800480 * Updates the scroll of the current page immediately to its final scroll position. We use this
481 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
482 * the previous tab page.
483 */
484 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700485 // If the current page is invalid, just reset the scroll position to zero
486 int newX = 0;
487 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700488 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700489 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800490 scrollTo(newX, 0);
491 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800492 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800493 }
494
495 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700496 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
497 * ends, {@link #resumeScrolling()} should be called, along with
498 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
499 */
500 void pauseScrolling() {
501 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700502 }
503
504 /**
505 * Enables scrolling again.
506 * @see #pauseScrolling()
507 */
508 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700509 }
510 /**
Winson Chung86f77532010-08-24 11:08:22 -0700511 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700512 */
Winson Chung86f77532010-08-24 11:08:22 -0700513 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800514 if (!mScroller.isFinished()) {
515 mScroller.abortAnimation();
516 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800517 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
518 // the default
519 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800520 return;
521 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700522
Adam Cohene61a9a22013-06-11 15:45:31 -0700523 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700524 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700525 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700526 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800527 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700528 }
529
Winson Chung8c87cd82013-07-23 16:20:10 -0700530 /**
531 * The restore page will be set in place of the current page at the next (likely first)
532 * layout.
533 */
534 void setRestorePage(int restorePage) {
535 mRestorePage = restorePage;
536 }
537
Michael Jurka0142d492010-08-25 17:46:15 -0700538 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700539 if (mPageSwitchListener != null) {
540 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700541 }
Winson Chungd2be3812013-07-16 11:11:32 -0700542
543 // Update the page indicator (when we aren't reordering)
544 if (mPageIndicator != null && !isReordering(false)) {
545 mPageIndicator.setActiveMarker(getNextPage());
546 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700547 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800548 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700549 if (!mIsPageMoving) {
550 mIsPageMoving = true;
551 onPageBeginMoving();
552 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700553 }
554
Michael Jurkace7e05f2011-02-01 22:02:35 -0800555 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700556 if (mIsPageMoving) {
557 mIsPageMoving = false;
558 onPageEndMoving();
559 }
Michael Jurka0142d492010-08-25 17:46:15 -0700560 }
561
Adam Cohen26976d92011-03-22 15:33:33 -0700562 protected boolean isPageMoving() {
563 return mIsPageMoving;
564 }
565
Michael Jurka0142d492010-08-25 17:46:15 -0700566 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700567 protected void onPageBeginMoving() {
568 }
569
570 // a method that subclasses can override to add behavior
571 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700572 }
573
Winson Chung321e9ee2010-08-09 13:37:56 -0700574 /**
Winson Chung86f77532010-08-24 11:08:22 -0700575 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700576 *
577 * @param l The listener used to respond to long clicks.
578 */
579 @Override
580 public void setOnLongClickListener(OnLongClickListener l) {
581 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700582 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700583 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700584 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700585 }
586 }
587
588 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800589 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700590 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800591 }
592
593 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700594 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700595 // In free scroll mode, we clamp the scrollX
596 if (mFreeScroll) {
597 x = Math.min(x, mFreeScrollMaxScrollX);
598 x = Math.max(x, mFreeScrollMinScrollX);
599 }
600
Adam Cohen0ffac432013-07-10 11:19:26 -0700601 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800602 mUnboundedScrollX = x;
603
Adam Cohen0ffac432013-07-10 11:19:26 -0700604 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
605 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
606 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800607 super.scrollTo(0, y);
608 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700609 if (isRtl) {
610 overScroll(x - mMaxScrollX);
611 } else {
612 overScroll(x);
613 }
Adam Cohen68d73932010-11-15 10:50:58 -0800614 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700615 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800616 super.scrollTo(mMaxScrollX, y);
617 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700618 if (isRtl) {
619 overScroll(x);
620 } else {
621 overScroll(x - mMaxScrollX);
622 }
Adam Cohen68d73932010-11-15 10:50:58 -0800623 }
624 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800625 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800626 super.scrollTo(x, y);
627 }
628
Michael Jurka0142d492010-08-25 17:46:15 -0700629 mTouchX = x;
630 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700631
632 // Update the last motion events when scrolling
633 if (isReordering(true)) {
634 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
635 mLastMotionX = p[0];
636 mLastMotionY = p[1];
637 updateDragViewTranslationDuringDrag();
638 }
Michael Jurka0142d492010-08-25 17:46:15 -0700639 }
640
641 // we moved this functionality to a helper function so SmoothPagedView can reuse it
642 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700643 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700644 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700645 if (getScrollX() != mScroller.getCurrX()
646 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700647 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700648 float scaleX = mFreeScroll ? getScaleX() : 1f;
649 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
650 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700651 }
Michael Jurka0142d492010-08-25 17:46:15 -0700652 invalidate();
653 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700654 } else if (mNextPage != INVALID_PAGE) {
655 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700656 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700657 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700658
Winson Chung9c0565f2013-07-19 13:49:06 -0700659 // Load the associated pages if necessary
660 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
661 loadAssociatedPages(mCurrentPage);
662 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
663 }
664
Adam Cohen73aa9752010-11-24 16:26:58 -0800665 // We don't want to trigger a page end moving unless the page has settled
666 // and the user has stopped scrolling
667 if (mTouchState == TOUCH_STATE_REST) {
668 pageEndMoving();
669 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700670
Adam Cohen7d30a372013-07-01 17:03:59 -0700671 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700672 // Notify the user when the page changes
673 AccessibilityManager accessibilityManager = (AccessibilityManager)
674 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
675 if (accessibilityManager.isEnabled()) {
676 AccessibilityEvent ev =
677 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
678 ev.getText().add(getCurrentPageDescription());
679 sendAccessibilityEventUnchecked(ev);
680 }
Michael Jurka0142d492010-08-25 17:46:15 -0700681 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700682 }
Michael Jurka0142d492010-08-25 17:46:15 -0700683 return false;
684 }
685
686 @Override
687 public void computeScroll() {
688 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700689 }
690
Adam Cohen7d30a372013-07-01 17:03:59 -0700691 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
692 return mTopAlignPageWhenShrinkingForBouncer;
693 }
694
Adam Cohen96d30a12013-07-16 18:13:21 -0700695 public static class LayoutParams extends ViewGroup.LayoutParams {
696 public boolean isFullScreenPage = false;
697
698 /**
699 * {@inheritDoc}
700 */
701 public LayoutParams(int width, int height) {
702 super(width, height);
703 }
704
705 public LayoutParams(ViewGroup.LayoutParams source) {
706 super(source);
707 }
708 }
709
710 protected LayoutParams generateDefaultLayoutParams() {
711 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
712 }
713
Adam Cohenedb40762013-07-18 16:45:45 -0700714 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700715 LayoutParams lp = generateDefaultLayoutParams();
716 lp.isFullScreenPage = true;
717 super.addView(page, 0, lp);
718 }
719
Winson Chung321e9ee2010-08-09 13:37:56 -0700720 @Override
721 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700722 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700723 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
724 return;
725 }
726
Adam Cohen7d30a372013-07-01 17:03:59 -0700727 // We measure the dimensions of the PagedView to be larger than the pages so that when we
728 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700729 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
730 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
731 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700732 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700733 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
734 // viewport, we can be at most one and a half screens offset once we scale down
735 DisplayMetrics dm = getResources().getDisplayMetrics();
736 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
Winson Chungc58497e2013-09-03 17:48:37 -0700737 int parentWidthSize, parentHeightSize;
738 int scaledWidthSize, scaledHeightSize;
739 if (mUseMinScale) {
740 parentWidthSize = (int) (1.5f * maxSize);
741 parentHeightSize = maxSize;
742 scaledWidthSize = (int) (parentWidthSize / mMinScale);
743 scaledHeightSize = (int) (parentHeightSize / mMinScale);
744 } else {
745 scaledWidthSize = widthSize;
746 scaledHeightSize = heightSize;
747 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700748 mViewport.set(0, 0, widthSize, heightSize);
749
750 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
751 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
752 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700753 }
754
Winson Chung8aad6102012-05-11 16:27:49 -0700755 // Return early if we aren't given a proper dimension
756 if (widthSize <= 0 || heightSize <= 0) {
757 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
758 return;
759 }
760
Adam Lesinski6b879f02010-11-04 16:15:23 -0700761 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
762 * of the All apps view on XLarge displays to not take up more space then it needs. Width
763 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
764 * each page to have the same width.
765 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700766 final int verticalPadding = getPaddingTop() + getPaddingBottom();
767 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700768
769 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700770 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700771 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700772 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
773 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
774 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
775 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700776 final int childCount = getChildCount();
777 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700778 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700779 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700780 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
781
782 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700783 int childHeightMode;
784 int childWidth;
785 int childHeight;
786
787 if (!lp.isFullScreenPage) {
788 if (lp.width == LayoutParams.WRAP_CONTENT) {
789 childWidthMode = MeasureSpec.AT_MOST;
790 } else {
791 childWidthMode = MeasureSpec.EXACTLY;
792 }
793
794 if (lp.height == LayoutParams.WRAP_CONTENT) {
795 childHeightMode = MeasureSpec.AT_MOST;
796 } else {
797 childHeightMode = MeasureSpec.EXACTLY;
798 }
799
800 childWidth = widthSize - horizontalPadding;
801 childHeight = heightSize - verticalPadding;
802
Michael Jurka5f1c5092010-09-03 14:15:02 -0700803 } else {
804 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700805 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700806
Winson Chungc58497e2013-09-03 17:48:37 -0700807 if (mUseMinScale) {
808 childWidth = getViewportWidth();
809 childHeight = getViewportHeight();
810 } else {
811 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
812 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
813 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700814 }
815
816 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700817 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
818 final int childHeightMeasureSpec =
819 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700820 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700821 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700822 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700823
Winson Chunga128a7b2012-04-30 15:23:15 -0700824 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700825 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700826 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700827 // The gap between pages in the PagedView should be equal to the gap from the page
828 // to the edge of the screen (so it is not visible in the current screen). To
829 // account for unequal padding on each side of the paged view, we take the maximum
830 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700831 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700832 int spacing = Math.max(offset, widthSize - offset -
833 getChildAt(0).getMeasuredWidth());
834 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700835 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700836 }
837 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700838 }
839
Adam Cohen60b07122011-11-14 17:26:06 -0800840 public void setPageSpacing(int pageSpacing) {
841 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700842 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800843 }
844
Winson Chung321e9ee2010-08-09 13:37:56 -0700845 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700846 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700847 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700848 return;
849 }
850
Winson Chung785d2eb2011-04-14 16:08:02 -0700851 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700852 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700853
Adam Cohenedb40762013-07-18 16:45:45 -0700854 int screenWidth = getViewportWidth();
855
Adam Cohen7d30a372013-07-01 17:03:59 -0700856 int offsetX = getViewportOffsetX();
857 int offsetY = getViewportOffsetY();
858
859 // Update the viewport offsets
860 mViewport.offset(offsetX, offsetY);
861
Adam Cohen0ffac432013-07-10 11:19:26 -0700862 final boolean isRtl = isLayoutRtl();
863
864 final int startIndex = isRtl ? childCount - 1 : 0;
865 final int endIndex = isRtl ? -1 : childCount;
866 final int delta = isRtl ? -1 : 1;
867
Adam Cohen7d30a372013-07-01 17:03:59 -0700868 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700869 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
870
871 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
872 mPageScrolls = new int[getChildCount()];
873 }
874
Adam Cohen0ffac432013-07-10 11:19:26 -0700875 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700876
Adam Cohen22f823d2011-09-01 17:22:18 -0700877 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700878 LayoutParams lp = (LayoutParams) child.getLayoutParams();
879 int childTop;
880
881 if (lp.isFullScreenPage) {
882 childTop = offsetY;
883 } else {
884 childTop = offsetY + getPaddingTop();
885 if (mCenterPagesVertically) {
886 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
887 }
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) {
1082 return child.getAlpha() > 0;
1083 }
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);
1549
1550 for (int i = 0; i < getPageCount(); ++i) {
1551 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
1552 getPageAt(i).setAlpha(1f);
1553 }
1554 }
1555 } else {
1556 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1557 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1558
1559 for (int i = 0; i < getPageCount(); ++i) {
1560 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
1561 getPageAt(i).setAlpha(0f);
1562 }
1563 }
1564
1565 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1566 setCurrentPage(mTempVisiblePagesRange[0]);
1567 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1568 setCurrentPage(mTempVisiblePagesRange[1]);
1569 }
1570 }
1571
1572 setEnableOverscroll(!freeScroll);
1573 }
1574
1575 private void setEnableOverscroll(boolean enable) {
1576 mAllowOverScroll = enable;
1577 }
1578
1579 int getNearestHoverOverPageIndex() {
1580 if (mDragView != null) {
1581 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1582 + mDragView.getTranslationX());
1583 getOverviewModePages(mTempVisiblePagesRange);
1584 int minDistance = Integer.MAX_VALUE;
1585 int minIndex = indexOfChild(mDragView);
1586 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1587 View page = getPageAt(i);
1588 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1589 int d = Math.abs(dragX - pageX);
1590 if (d < minDistance) {
1591 minIndex = i;
1592 minDistance = d;
1593 }
1594 }
1595 return minIndex;
1596 }
1597 return -1;
1598 }
1599
Winson Chung321e9ee2010-08-09 13:37:56 -07001600 @Override
1601 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001602 if (DISABLE_TOUCH_INTERACTION) {
1603 return false;
1604 }
1605
Winson Chung45e1d6e2010-11-09 17:19:49 -08001606 // Skip touch handling if there are no pages to swipe
1607 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1608
Michael Jurkab8f06722010-10-10 15:58:46 -07001609 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001610
1611 final int action = ev.getAction();
1612
1613 switch (action & MotionEvent.ACTION_MASK) {
1614 case MotionEvent.ACTION_DOWN:
1615 /*
1616 * If being flinged and user touches, stop the fling. isFinished
1617 * will be false if being flinged.
1618 */
1619 if (!mScroller.isFinished()) {
1620 mScroller.abortAnimation();
1621 }
1622
1623 // Remember where the motion event started
1624 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001625 mDownMotionY = mLastMotionY = ev.getY();
1626 mDownScrollX = getScrollX();
1627 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1628 mParentDownMotionX = p[0];
1629 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001630 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001631 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001632 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001633
Michael Jurka0142d492010-08-25 17:46:15 -07001634 if (mTouchState == TOUCH_STATE_SCROLLING) {
1635 pageBeginMoving();
1636 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001637 break;
1638
1639 case MotionEvent.ACTION_MOVE:
1640 if (mTouchState == TOUCH_STATE_SCROLLING) {
1641 // Scroll to follow the motion event
1642 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001643
1644 if (pointerIndex == -1) return true;
1645
Winson Chung321e9ee2010-08-09 13:37:56 -07001646 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001647 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001648
Adam Cohenaefd4e12011-02-14 16:39:38 -08001649 mTotalMotionX += Math.abs(deltaX);
1650
Winson Chungc0844aa2011-02-02 15:25:58 -08001651 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1652 // keep the remainder because we are actually testing if we've moved from the last
1653 // scrolled position (which is discrete).
1654 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001655 mTouchX += deltaX;
1656 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1657 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001658 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001659 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001660 } else {
1661 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001662 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001663 mLastMotionX = x;
1664 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001665 } else {
1666 awakenScrollBars();
1667 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001668 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1669 // Update the last motion position
1670 mLastMotionX = ev.getX();
1671 mLastMotionY = ev.getY();
1672
1673 // Update the parent down so that our zoom animations take this new movement into
1674 // account
1675 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1676 mParentDownMotionX = pt[0];
1677 mParentDownMotionY = pt[1];
1678 updateDragViewTranslationDuringDrag();
1679
1680 // Find the closest page to the touch point
1681 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001682
1683 // Change the drag view if we are hovering over the drop target
1684 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1685 (int) mParentDownMotionX, (int) mParentDownMotionY);
1686 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1687
Adam Cohen7d30a372013-07-01 17:03:59 -07001688 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1689 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1690 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1691 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1692
Adam Cohenf358a4b2013-07-23 16:47:31 -07001693 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1694 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1695 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001696 mTempVisiblePagesRange[0] = 0;
1697 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001698 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001699 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1700 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1701 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1702 mSidePageHoverIndex = pageUnderPointIndex;
1703 mSidePageHoverRunnable = new Runnable() {
1704 @Override
1705 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001706 // Setup the scroll to the correct page before we swap the views
1707 snapToPage(pageUnderPointIndex);
1708
1709 // For each of the pages between the paged view and the drag view,
1710 // animate them from the previous position to the new position in
1711 // the layout (as a result of the drag view moving in the layout)
1712 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1713 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1714 dragViewIndex + 1 : pageUnderPointIndex;
1715 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1716 dragViewIndex - 1 : pageUnderPointIndex;
1717 for (int i = lowerIndex; i <= upperIndex; ++i) {
1718 View v = getChildAt(i);
1719 // dragViewIndex < pageUnderPointIndex, so after we remove the
1720 // drag view all subsequent views to pageUnderPointIndex will
1721 // shift down.
1722 int oldX = getViewportOffsetX() + getChildOffset(i);
1723 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1724
1725 // Animate the view translation from its old position to its new
1726 // position
1727 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1728 if (anim != null) {
1729 anim.cancel();
1730 }
1731
1732 v.setTranslationX(oldX - newX);
1733 anim = new AnimatorSet();
1734 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1735 anim.playTogether(
1736 ObjectAnimator.ofFloat(v, "translationX", 0f));
1737 anim.start();
1738 v.setTag(anim);
1739 }
1740
1741 removeView(mDragView);
1742 onRemoveView(mDragView, false);
1743 addView(mDragView, pageUnderPointIndex);
1744 onAddView(mDragView, pageUnderPointIndex);
1745 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001746 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001747 }
1748 };
1749 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1750 }
1751 } else {
1752 removeCallbacks(mSidePageHoverRunnable);
1753 mSidePageHoverIndex = -1;
1754 }
Adam Cohen564976a2010-10-13 18:52:07 -07001755 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001756 determineScrollingStart(ev);
1757 }
1758 break;
1759
1760 case MotionEvent.ACTION_UP:
1761 if (mTouchState == TOUCH_STATE_SCROLLING) {
1762 final int activePointerId = mActivePointerId;
1763 final int pointerIndex = ev.findPointerIndex(activePointerId);
1764 final float x = ev.getX(pointerIndex);
1765 final VelocityTracker velocityTracker = mVelocityTracker;
1766 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1767 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001768 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001769 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001770 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1771 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001772
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001773 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1774
Adam Cohen00481b32011-11-18 12:03:48 -08001775 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001776 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001777
Adam Cohenf358a4b2013-07-23 16:47:31 -07001778 if (!mFreeScroll) {
1779 // In the case that the page is moved far to one direction and then is flung
1780 // in the opposite direction, we use a threshold to determine whether we should
1781 // just return to the starting page, or if we should skip one further.
1782 boolean returnToOriginalPage = false;
1783 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1784 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1785 returnToOriginalPage = true;
1786 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001787
Adam Cohenf358a4b2013-07-23 16:47:31 -07001788 int finalPage;
1789 // We give flings precedence over large moves, which is why we short-circuit our
1790 // test for a large move if a fling has been registered. That is, a large
1791 // move to the left and fling to the right will register as a fling to the right.
1792 final boolean isRtl = isLayoutRtl();
1793 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1794 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1795 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1796 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1797 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1798 snapToPageWithVelocity(finalPage, velocityX);
1799 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1800 (isFling && isVelocityXLeft)) &&
1801 mCurrentPage < getChildCount() - 1) {
1802 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1803 snapToPageWithVelocity(finalPage, velocityX);
1804 } else {
1805 snapToDestination();
1806 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1807 // at this point we have not moved beyond the touch slop
1808 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1809 // we can just page
1810 int nextPage = Math.max(0, mCurrentPage - 1);
1811 if (nextPage != mCurrentPage) {
1812 snapToPage(nextPage);
1813 } else {
1814 snapToDestination();
1815 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001816 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001817 if (!mScroller.isFinished()) {
1818 mScroller.abortAnimation();
1819 }
1820
1821 float scaleX = getScaleX();
1822 int vX = (int) (-velocityX * scaleX);
1823 int initialScrollX = (int) (getScrollX() * scaleX);
1824
1825 mScroller.fling(initialScrollX,
1826 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1827 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001828 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001829 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001830 // at this point we have not moved beyond the touch slop
1831 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1832 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001833 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1834 if (nextPage != mCurrentPage) {
1835 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001836 } else {
1837 snapToDestination();
1838 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001839 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1840 // Update the last motion position
1841 mLastMotionX = ev.getX();
1842 mLastMotionY = ev.getY();
1843
1844 // Update the parent down so that our zoom animations take this new movement into
1845 // account
1846 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1847 mParentDownMotionX = pt[0];
1848 mParentDownMotionY = pt[1];
1849 updateDragViewTranslationDuringDrag();
1850 boolean handledFling = false;
1851 if (!DISABLE_FLING_TO_DELETE) {
1852 // Check the velocity and see if we are flinging-to-delete
1853 PointF flingToDeleteVector = isFlingingToDelete();
1854 if (flingToDeleteVector != null) {
1855 onFlingToDelete(flingToDeleteVector);
1856 handledFling = true;
1857 }
1858 }
1859 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1860 (int) mParentDownMotionY)) {
1861 onDropToDelete();
1862 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001863 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001864 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001865 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001866
1867 // Remove the callback to wait for the side page hover timeout
1868 removeCallbacks(mSidePageHoverRunnable);
1869 // End any intermediate reordering states
1870 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001871 break;
1872
1873 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001874 if (mTouchState == TOUCH_STATE_SCROLLING) {
1875 snapToDestination();
1876 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001877 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001878 break;
1879
1880 case MotionEvent.ACTION_POINTER_UP:
1881 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001882 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001883 break;
1884 }
1885
1886 return true;
1887 }
1888
Adam Cohen7d30a372013-07-01 17:03:59 -07001889 public void onFlingToDelete(View v) {}
1890 public void onRemoveView(View v, boolean deletePermanently) {}
1891 public void onRemoveViewAnimationCompleted() {}
1892 public void onAddView(View v, int index) {}
1893
1894 private void resetTouchState() {
1895 releaseVelocityTracker();
1896 endReordering();
1897 mTouchState = TOUCH_STATE_REST;
1898 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001899 }
1900
1901 protected void onUnhandledTap(MotionEvent ev) {}
1902
Winson Chung185d7162011-02-28 13:47:29 -08001903 @Override
1904 public boolean onGenericMotionEvent(MotionEvent event) {
1905 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1906 switch (event.getAction()) {
1907 case MotionEvent.ACTION_SCROLL: {
1908 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1909 final float vscroll;
1910 final float hscroll;
1911 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1912 vscroll = 0;
1913 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1914 } else {
1915 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1916 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1917 }
1918 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001919 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1920 : (hscroll > 0 || vscroll > 0);
1921 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001922 scrollRight();
1923 } else {
1924 scrollLeft();
1925 }
1926 return true;
1927 }
1928 }
1929 }
1930 }
1931 return super.onGenericMotionEvent(event);
1932 }
1933
Michael Jurkab8f06722010-10-10 15:58:46 -07001934 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1935 if (mVelocityTracker == null) {
1936 mVelocityTracker = VelocityTracker.obtain();
1937 }
1938 mVelocityTracker.addMovement(ev);
1939 }
1940
1941 private void releaseVelocityTracker() {
1942 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001943 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001944 mVelocityTracker.recycle();
1945 mVelocityTracker = null;
1946 }
1947 }
1948
Winson Chung321e9ee2010-08-09 13:37:56 -07001949 private void onSecondaryPointerUp(MotionEvent ev) {
1950 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1951 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1952 final int pointerId = ev.getPointerId(pointerIndex);
1953 if (pointerId == mActivePointerId) {
1954 // This was our active pointer going up. Choose a new
1955 // active pointer and adjust accordingly.
1956 // TODO: Make this decision more intelligent.
1957 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1958 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1959 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001960 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001961 mActivePointerId = ev.getPointerId(newPointerIndex);
1962 if (mVelocityTracker != null) {
1963 mVelocityTracker.clear();
1964 }
1965 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001966 }
1967
Winson Chung321e9ee2010-08-09 13:37:56 -07001968 @Override
1969 public void requestChildFocus(View child, View focused) {
1970 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001971 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001972 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001973 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001974 }
1975 }
1976
Winson Chung1908d072011-02-24 18:09:44 -08001977 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001978 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001979 }
1980
Adam Cohen7d30a372013-07-01 17:03:59 -07001981 int getPageNearestToPoint(float x) {
1982 int index = 0;
1983 for (int i = 0; i < getChildCount(); ++i) {
1984 if (x < getChildAt(i).getRight() - getScrollX()) {
1985 return index;
1986 } else {
1987 index++;
1988 }
1989 }
1990 return Math.min(index, getChildCount() - 1);
1991 }
1992
Adam Cohend19d3ca2010-09-15 14:43:42 -07001993 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001994 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001995 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001996 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001997 final int childCount = getChildCount();
1998 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001999 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002000 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002001 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002002 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002003 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2004 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2005 minDistanceFromScreenCenter = distanceFromScreenCenter;
2006 minDistanceFromScreenCenterIndex = i;
2007 }
2008 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002009 return minDistanceFromScreenCenterIndex;
2010 }
2011
2012 protected void snapToDestination() {
2013 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002014 }
2015
Adam Cohene0f66b52010-11-23 15:06:07 -08002016 private static class ScrollInterpolator implements Interpolator {
2017 public ScrollInterpolator() {
2018 }
2019
2020 public float getInterpolation(float t) {
2021 t -= 1.0f;
2022 return t*t*t*t*t + 1;
2023 }
2024 }
2025
2026 // We want the duration of the page snap animation to be influenced by the distance that
2027 // the screen has to travel, however, we don't want this duration to be effected in a
2028 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2029 // of travel has on the overall snap duration.
2030 float distanceInfluenceForSnapDuration(float f) {
2031 f -= 0.5f; // center the values about 0.
2032 f *= 0.3f * Math.PI / 2.0f;
2033 return (float) Math.sin(f);
2034 }
2035
Michael Jurka0142d492010-08-25 17:46:15 -07002036 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002037 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002038 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002039
Adam Cohenedb40762013-07-18 16:45:45 -07002040 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002041 int delta = newX - mUnboundedScrollX;
2042 int duration = 0;
2043
Adam Cohen265b9a62011-12-07 14:37:18 -08002044 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002045 // If the velocity is low enough, then treat this more as an automatic page advance
2046 // as opposed to an apparent physical response to flinging
2047 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2048 return;
2049 }
2050
2051 // Here we compute a "distance" that will be used in the computation of the overall
2052 // snap duration. This is a function of the actual distance that needs to be traveled;
2053 // we keep this value close to half screen size in order to reduce the variance in snap
2054 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002055 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002056 float distance = halfScreenSize + halfScreenSize *
2057 distanceInfluenceForSnapDuration(distanceRatio);
2058
2059 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002060 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002061
2062 // we want the page's snap velocity to approximately match the velocity at which the
2063 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002064 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2065 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002066
2067 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002068 }
2069
2070 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002071 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002072 }
2073
Adam Cohen7d30a372013-07-01 17:03:59 -07002074 protected void snapToPageImmediately(int whichPage) {
2075 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2076 }
2077
Michael Jurka0142d492010-08-25 17:46:15 -07002078 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002079 snapToPage(whichPage, duration, false);
2080 }
2081
2082 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002083 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002084
Adam Cohenedb40762013-07-18 16:45:45 -07002085 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002086 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002087 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002088 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002089 }
2090
2091 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002092 snapToPage(whichPage, delta, duration, false);
2093 }
Michael Jurka0142d492010-08-25 17:46:15 -07002094
Adam Cohen7d30a372013-07-01 17:03:59 -07002095 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2096 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002097 View focusedChild = getFocusedChild();
2098 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002099 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002100 focusedChild.clearFocus();
2101 }
2102
2103 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002104 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002105 if (immediate) {
2106 duration = 0;
2107 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002108 duration = Math.abs(delta);
2109 }
2110
Adam Cohenf358a4b2013-07-23 16:47:31 -07002111 if (!mScroller.isFinished()) {
2112 mScroller.abortAnimation();
2113 }
Adam Cohen68d73932010-11-15 10:50:58 -08002114 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002115
Michael Jurka0142d492010-08-25 17:46:15 -07002116 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002117
2118 // Trigger a compute() to finish switching pages if necessary
2119 if (immediate) {
2120 computeScroll();
2121 }
2122
Winson Chung9c0565f2013-07-19 13:49:06 -07002123 // Defer loading associated pages until the scroll settles
2124 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2125
Adam Cohen7d30a372013-07-01 17:03:59 -07002126 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002127 invalidate();
2128 }
2129
Winson Chung321e9ee2010-08-09 13:37:56 -07002130 public void scrollLeft() {
2131 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002132 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002133 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002134 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002135 }
2136 }
2137
2138 public void scrollRight() {
2139 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002140 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002141 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002142 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002143 }
2144 }
2145
Winson Chung86f77532010-08-24 11:08:22 -07002146 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002147 int result = -1;
2148 if (v != null) {
2149 ViewParent vp = v.getParent();
2150 int count = getChildCount();
2151 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002152 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002153 return i;
2154 }
2155 }
2156 }
2157 return result;
2158 }
2159
2160 /**
2161 * @return True is long presses are still allowed for the current touch
2162 */
2163 public boolean allowLongPress() {
2164 return mAllowLongPress;
2165 }
2166
Michael Jurka0142d492010-08-25 17:46:15 -07002167 /**
2168 * Set true to allow long-press events to be triggered, usually checked by
2169 * {@link Launcher} to accept or block dpad-initiated long-presses.
2170 */
2171 public void setAllowLongPress(boolean allowLongPress) {
2172 mAllowLongPress = allowLongPress;
2173 }
2174
Winson Chung321e9ee2010-08-09 13:37:56 -07002175 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002176 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002177
2178 SavedState(Parcelable superState) {
2179 super(superState);
2180 }
2181
2182 private SavedState(Parcel in) {
2183 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002184 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002185 }
2186
2187 @Override
2188 public void writeToParcel(Parcel out, int flags) {
2189 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002190 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002191 }
2192
2193 public static final Parcelable.Creator<SavedState> CREATOR =
2194 new Parcelable.Creator<SavedState>() {
2195 public SavedState createFromParcel(Parcel in) {
2196 return new SavedState(in);
2197 }
2198
2199 public SavedState[] newArray(int size) {
2200 return new SavedState[size];
2201 }
2202 };
2203 }
2204
Winson Chungf314b0e2011-08-16 11:54:27 -07002205 protected void loadAssociatedPages(int page) {
2206 loadAssociatedPages(page, false);
2207 }
2208 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002209 if (mContentIsRefreshable) {
2210 final int count = getChildCount();
2211 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002212 int lowerPageBound = getAssociatedLowerPageBound(page);
2213 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002214 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2215 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002216 // First, clear any pages that should no longer be loaded
2217 for (int i = 0; i < count; ++i) {
2218 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002219 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002220 if (layout.getPageChildCount() > 0) {
2221 layout.removeAllViewsOnPage();
2222 }
2223 mDirtyPageContent.set(i, true);
2224 }
2225 }
2226 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002227 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002228 if ((i != page) && immediateAndOnly) {
2229 continue;
2230 }
Michael Jurka0142d492010-08-25 17:46:15 -07002231 if (lowerPageBound <= i && i <= upperPageBound) {
2232 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002233 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002234 mDirtyPageContent.set(i, false);
2235 }
Winson Chung86f77532010-08-24 11:08:22 -07002236 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002237 }
2238 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002239 }
2240 }
2241
Winson Chunge3193b92010-09-10 11:44:42 -07002242 protected int getAssociatedLowerPageBound(int page) {
2243 return Math.max(0, page - 1);
2244 }
2245 protected int getAssociatedUpperPageBound(int page) {
2246 final int count = getChildCount();
2247 return Math.min(page + 1, count - 1);
2248 }
2249
Winson Chung86f77532010-08-24 11:08:22 -07002250 /**
2251 * This method is called ONLY to synchronize the number of pages that the paged view has.
2252 * To actually fill the pages with information, implement syncPageItems() below. It is
2253 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2254 * and therefore, individual page items do not need to be updated in this method.
2255 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002256 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002257
2258 /**
2259 * This method is called to synchronize the items that are on a particular page. If views on
2260 * the page can be reused, then they should be updated within this method.
2261 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002262 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002263
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002264 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002265 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002266 }
2267 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002268 invalidatePageData(currentPage, false);
2269 }
2270 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002271 if (!mIsDataReady) {
2272 return;
2273 }
2274
Michael Jurka0142d492010-08-25 17:46:15 -07002275 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002276 // Force all scrolling-related behavior to end
2277 mScroller.forceFinished(true);
2278 mNextPage = INVALID_PAGE;
2279
Michael Jurka0142d492010-08-25 17:46:15 -07002280 // Update all the pages
2281 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002282
Winson Chung5a808352011-06-27 19:08:49 -07002283 // We must force a measure after we've loaded the pages to update the content width and
2284 // to determine the full scroll width
2285 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2286 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2287
2288 // Set a new page as the current page if necessary
2289 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002290 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002291 }
2292
Michael Jurka0142d492010-08-25 17:46:15 -07002293 // Mark each of the pages as dirty
2294 final int count = getChildCount();
2295 mDirtyPageContent.clear();
2296 for (int i = 0; i < count; ++i) {
2297 mDirtyPageContent.add(true);
2298 }
2299
2300 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002301 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002302 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002303 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002304 }
Winson Chung007c6982011-06-14 13:27:53 -07002305
Adam Cohen7d30a372013-07-01 17:03:59 -07002306 // Animate the drag view back to the original position
2307 void animateDragViewToOriginalPosition() {
2308 if (mDragView != null) {
2309 AnimatorSet anim = new AnimatorSet();
2310 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2311 anim.playTogether(
2312 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002313 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2314 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2315 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002316 anim.addListener(new AnimatorListenerAdapter() {
2317 @Override
2318 public void onAnimationEnd(Animator animation) {
2319 onPostReorderingAnimationCompleted();
2320 }
2321 });
2322 anim.start();
2323 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002324 }
2325
Adam Cohen7d30a372013-07-01 17:03:59 -07002326 protected void onStartReordering() {
2327 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2328 mTouchState = TOUCH_STATE_REORDERING;
2329 mIsReordering = true;
2330
Adam Cohen7d30a372013-07-01 17:03:59 -07002331 // We must invalidate to trigger a redraw to update the layers such that the drag view
2332 // is always drawn on top
2333 invalidate();
2334 }
2335
2336 private void onPostReorderingAnimationCompleted() {
2337 // Trigger the callback when reordering has settled
2338 --mPostReorderingPreZoomInRemainingAnimationCount;
2339 if (mPostReorderingPreZoomInRunnable != null &&
2340 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2341 mPostReorderingPreZoomInRunnable.run();
2342 mPostReorderingPreZoomInRunnable = null;
2343 }
2344 }
2345
2346 protected void onEndReordering() {
2347 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002348 }
2349
Adam Cohenf358a4b2013-07-23 16:47:31 -07002350 public boolean startReordering(View v) {
2351 int dragViewIndex = indexOfChild(v);//getPageNearestToCenterOfScreen();
Adam Cohen7d30a372013-07-01 17:03:59 -07002352 mTempVisiblePagesRange[0] = 0;
2353 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002354 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002355 mReorderingStarted = true;
2356
2357 // Check if we are within the reordering range
2358 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002359 dragViewIndex <= mTempVisiblePagesRange[1]) {
2360 // Find the drag view under the pointer
2361 mDragView = getChildAt(dragViewIndex);
2362 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2363 mDragViewBaselineLeft = mDragView.getLeft();
2364 disableFreeScroll(-1);
2365 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002366 return true;
2367 }
2368 return false;
2369 }
2370
2371 boolean isReordering(boolean testTouchState) {
2372 boolean state = mIsReordering;
2373 if (testTouchState) {
2374 state &= (mTouchState == TOUCH_STATE_REORDERING);
2375 }
2376 return state;
2377 }
2378 void endReordering() {
2379 // For simplicity, we call endReordering sometimes even if reordering was never started.
2380 // In that case, we don't want to do anything.
2381 if (!mReorderingStarted) return;
2382 mReorderingStarted = false;
2383
2384 // If we haven't flung-to-delete the current child, then we just animate the drag view
2385 // back into position
2386 final Runnable onCompleteRunnable = new Runnable() {
2387 @Override
2388 public void run() {
2389 onEndReordering();
2390 }
2391 };
2392 if (!mDeferringForDelete) {
2393 mPostReorderingPreZoomInRunnable = new Runnable() {
2394 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002395 onCompleteRunnable.run();
2396 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002397 };
2398 };
2399
2400 mPostReorderingPreZoomInRemainingAnimationCount =
2401 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2402 // Snap to the current page
2403 snapToPage(indexOfChild(mDragView), 0);
2404 // Animate the drag view back to the front position
2405 animateDragViewToOriginalPosition();
2406 } else {
2407 // Handled in post-delete-animation-callbacks
2408 }
2409 }
2410
Adam Cohen7d30a372013-07-01 17:03:59 -07002411 /*
2412 * Flinging to delete - IN PROGRESS
2413 */
2414 private PointF isFlingingToDelete() {
2415 ViewConfiguration config = ViewConfiguration.get(getContext());
2416 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2417
2418 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2419 // Do a quick dot product test to ensure that we are flinging upwards
2420 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2421 mVelocityTracker.getYVelocity());
2422 PointF upVec = new PointF(0f, -1f);
2423 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2424 (vel.length() * upVec.length()));
2425 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2426 return vel;
2427 }
2428 }
2429 return null;
2430 }
2431
2432 /**
2433 * Creates an animation from the current drag view along its current velocity vector.
2434 * For this animation, the alpha runs for a fixed duration and we update the position
2435 * progressively.
2436 */
2437 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2438 private View mDragView;
2439 private PointF mVelocity;
2440 private Rect mFrom;
2441 private long mPrevTime;
2442 private float mFriction;
2443
2444 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2445
2446 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2447 long startTime, float friction) {
2448 mDragView = dragView;
2449 mVelocity = vel;
2450 mFrom = from;
2451 mPrevTime = startTime;
2452 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2453 }
2454
2455 @Override
2456 public void onAnimationUpdate(ValueAnimator animation) {
2457 float t = ((Float) animation.getAnimatedValue()).floatValue();
2458 long curTime = AnimationUtils.currentAnimationTimeMillis();
2459
2460 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2461 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2462
2463 mDragView.setTranslationX(mFrom.left);
2464 mDragView.setTranslationY(mFrom.top);
2465 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2466
2467 mVelocity.x *= mFriction;
2468 mVelocity.y *= mFriction;
2469 mPrevTime = curTime;
2470 }
2471 };
2472
2473 private static final int ANIM_TAG_KEY = 100;
2474
2475 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2476 return new Runnable() {
2477 @Override
2478 public void run() {
2479 int dragViewIndex = indexOfChild(dragView);
2480
2481 // For each of the pages around the drag view, animate them from the previous
2482 // position to the new position in the layout (as a result of the drag view moving
2483 // in the layout)
2484 // NOTE: We can make an assumption here because we have side-bound pages that we
2485 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002486 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002487 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2488 boolean slideFromLeft = (isLastWidgetPage ||
2489 dragViewIndex > mTempVisiblePagesRange[0]);
2490
2491 // Setup the scroll to the correct page before we swap the views
2492 if (slideFromLeft) {
2493 snapToPageImmediately(dragViewIndex - 1);
2494 }
2495
2496 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2497 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2498 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2499 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2500 ArrayList<Animator> animations = new ArrayList<Animator>();
2501 for (int i = lowerIndex; i <= upperIndex; ++i) {
2502 View v = getChildAt(i);
2503 // dragViewIndex < pageUnderPointIndex, so after we remove the
2504 // drag view all subsequent views to pageUnderPointIndex will
2505 // shift down.
2506 int oldX = 0;
2507 int newX = 0;
2508 if (slideFromLeft) {
2509 if (i == 0) {
2510 // Simulate the page being offscreen with the page spacing
2511 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2512 - mPageSpacing;
2513 } else {
2514 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2515 }
2516 newX = getViewportOffsetX() + getChildOffset(i);
2517 } else {
2518 oldX = getChildOffset(i) - getChildOffset(i - 1);
2519 newX = 0;
2520 }
2521
2522 // Animate the view translation from its old position to its new
2523 // position
2524 AnimatorSet anim = (AnimatorSet) v.getTag();
2525 if (anim != null) {
2526 anim.cancel();
2527 }
2528
2529 // Note: Hacky, but we want to skip any optimizations to not draw completely
2530 // hidden views
2531 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2532 v.setTranslationX(oldX - newX);
2533 anim = new AnimatorSet();
2534 anim.playTogether(
2535 ObjectAnimator.ofFloat(v, "translationX", 0f),
2536 ObjectAnimator.ofFloat(v, "alpha", 1f));
2537 animations.add(anim);
2538 v.setTag(ANIM_TAG_KEY, anim);
2539 }
2540
2541 AnimatorSet slideAnimations = new AnimatorSet();
2542 slideAnimations.playTogether(animations);
2543 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2544 slideAnimations.addListener(new AnimatorListenerAdapter() {
2545 @Override
2546 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002547 mDeferringForDelete = false;
2548 onEndReordering();
2549 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002550 }
2551 });
2552 slideAnimations.start();
2553
2554 removeView(dragView);
2555 onRemoveView(dragView, true);
2556 }
2557 };
2558 }
2559
2560 public void onFlingToDelete(PointF vel) {
2561 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2562
2563 // NOTE: Because it takes time for the first frame of animation to actually be
2564 // called and we expect the animation to be a continuation of the fling, we have
2565 // to account for the time that has elapsed since the fling finished. And since
2566 // we don't have a startDelay, we will always get call to update when we call
2567 // start() (which we want to ignore).
2568 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2569 private int mCount = -1;
2570 private long mStartTime;
2571 private float mOffset;
2572 /* Anonymous inner class ctor */ {
2573 mStartTime = startTime;
2574 }
2575
2576 @Override
2577 public float getInterpolation(float t) {
2578 if (mCount < 0) {
2579 mCount++;
2580 } else if (mCount == 0) {
2581 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2582 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2583 mCount++;
2584 }
2585 return Math.min(1f, mOffset + t);
2586 }
2587 };
2588
2589 final Rect from = new Rect();
2590 final View dragView = mDragView;
2591 from.left = (int) dragView.getTranslationX();
2592 from.top = (int) dragView.getTranslationY();
2593 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2594 from, startTime, FLING_TO_DELETE_FRICTION);
2595
2596 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2597
2598 // Create and start the animation
2599 ValueAnimator mDropAnim = new ValueAnimator();
2600 mDropAnim.setInterpolator(tInterpolator);
2601 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2602 mDropAnim.setFloatValues(0f, 1f);
2603 mDropAnim.addUpdateListener(updateCb);
2604 mDropAnim.addListener(new AnimatorListenerAdapter() {
2605 public void onAnimationEnd(Animator animation) {
2606 onAnimationEndRunnable.run();
2607 }
2608 });
2609 mDropAnim.start();
2610 mDeferringForDelete = true;
2611 }
2612
2613 /* Drag to delete */
2614 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2615 if (mDeleteDropTarget != null) {
2616 mAltTmpRect.set(0, 0, 0, 0);
2617 View parent = (View) mDeleteDropTarget.getParent();
2618 if (parent != null) {
2619 parent.getGlobalVisibleRect(mAltTmpRect);
2620 }
2621 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2622 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2623 return mTmpRect.contains(x, y);
2624 }
2625 return false;
2626 }
2627
2628 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2629
2630 private void onDropToDelete() {
2631 final View dragView = mDragView;
2632
2633 final float toScale = 0f;
2634 final float toAlpha = 0f;
2635
2636 // Create and start the complex animation
2637 ArrayList<Animator> animations = new ArrayList<Animator>();
2638 AnimatorSet motionAnim = new AnimatorSet();
2639 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2640 motionAnim.playTogether(
2641 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2642 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2643 animations.add(motionAnim);
2644
2645 AnimatorSet alphaAnim = new AnimatorSet();
2646 alphaAnim.setInterpolator(new LinearInterpolator());
2647 alphaAnim.playTogether(
2648 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2649 animations.add(alphaAnim);
2650
2651 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2652
2653 AnimatorSet anim = new AnimatorSet();
2654 anim.playTogether(animations);
2655 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2656 anim.addListener(new AnimatorListenerAdapter() {
2657 public void onAnimationEnd(Animator animation) {
2658 onAnimationEndRunnable.run();
2659 }
2660 });
2661 anim.start();
2662
2663 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002664 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002665
2666 /* Accessibility */
2667 @Override
2668 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2669 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002670 info.setScrollable(getPageCount() > 1);
2671 if (getCurrentPage() < getPageCount() - 1) {
2672 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2673 }
2674 if (getCurrentPage() > 0) {
2675 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2676 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002677 }
2678
2679 @Override
2680 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2681 super.onInitializeAccessibilityEvent(event);
2682 event.setScrollable(true);
2683 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2684 event.setFromIndex(mCurrentPage);
2685 event.setToIndex(mCurrentPage);
2686 event.setItemCount(getChildCount());
2687 }
2688 }
2689
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002690 @Override
2691 public boolean performAccessibilityAction(int action, Bundle arguments) {
2692 if (super.performAccessibilityAction(action, arguments)) {
2693 return true;
2694 }
2695 switch (action) {
2696 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2697 if (getCurrentPage() < getPageCount() - 1) {
2698 scrollRight();
2699 return true;
2700 }
2701 } break;
2702 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2703 if (getCurrentPage() > 0) {
2704 scrollLeft();
2705 return true;
2706 }
2707 } break;
2708 }
2709 return false;
2710 }
2711
Adam Cohen0ffac432013-07-10 11:19:26 -07002712 protected String getCurrentPageDescription() {
2713 return String.format(getContext().getString(R.string.default_scroll_format),
2714 getNextPage() + 1, getChildCount());
2715 }
2716
Winson Chungd11265e2011-08-30 13:37:23 -07002717 @Override
2718 public boolean onHoverEvent(android.view.MotionEvent event) {
2719 return true;
2720 }
Adam Cohenf358a4b2013-07-23 16:47:31 -07002721}