blob: ccf21561d966f6f9d572ec3c36aa10cf2a35ff36 [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen7d30a372013-07-01 17:03:59 -070027import android.content.res.Resources;
Adam Cohen9c4949e2010-10-05 12:27:22 -070028import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070029import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070030import android.graphics.Matrix;
31import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070032import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070033import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070034import android.os.Parcel;
35import android.os.Parcelable;
36import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070037import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070038import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080039import android.view.InputDevice;
40import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070041import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewGroup;
46import android.view.ViewParent;
Adam Cohen96d30a12013-07-16 18:13:21 -070047import android.view.ViewGroup.LayoutParams;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070049import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070050import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070051import android.view.animation.AnimationUtils;
52import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080053import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070054import android.view.animation.LinearInterpolator;
Adam Cohen96d30a12013-07-16 18:13:21 -070055import android.widget.FrameLayout;
Winson Chung321e9ee2010-08-09 13:37:56 -070056import android.widget.Scroller;
57
Winson Chung6a0f57d2011-06-29 20:10:49 -070058import java.util.ArrayList;
59
Winson Chung321e9ee2010-08-09 13:37:56 -070060/**
61 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070062 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070063 */
Michael Jurka8b805b12012-04-18 14:23:14 -070064public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070065 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070066 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070067 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070068
Winson Chung86f77532010-08-24 11:08:22 -070069 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070070 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070071
Adam Cohen7d30a372013-07-01 17:03:59 -070072 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070073 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070074 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070075
Adam Cohenb5ba0972011-09-07 18:02:31 -070076 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070077 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080078
Adam Cohenb64cb5a2011-02-15 13:53:42 -080079 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080080 // The page is moved more than halfway, automatically move to the next page on touch up.
81 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080082
Adam Cohen265b9a62011-12-07 14:37:18 -080083 // The following constants need to be scaled based on density. The scaled versions will be
84 // assigned to the corresponding member variables below.
85 private static final int FLING_THRESHOLD_VELOCITY = 500;
86 private static final int MIN_SNAP_VELOCITY = 1500;
87 private static final int MIN_FLING_VELOCITY = 250;
88
Adam Cohen7d30a372013-07-01 17:03:59 -070089 // We are disabling touch interaction of the widget region for factory ROM.
90 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070091 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070092 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070093
Adam Cohenf358a4b2013-07-23 16:47:31 -070094 private boolean mFreeScroll = false;
95 private int mFreeScrollMinScrollX = -1;
96 private int mFreeScrollMaxScrollX = -1;
97
Winson Chung8aad6102012-05-11 16:27:49 -070098 static final int AUTOMATIC_PAGE_SPACING = -1;
99
Adam Cohen265b9a62011-12-07 14:37:18 -0800100 protected int mFlingThresholdVelocity;
101 protected int mMinFlingVelocity;
102 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700103
Adam Cohenb5ba0972011-09-07 18:02:31 -0700104 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700105 protected float mSmoothingTime;
106 protected float mTouchX;
107
108 protected boolean mFirstLayout = true;
109
110 protected int mCurrentPage;
Winson Chung8c87cd82013-07-23 16:20:10 -0700111 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700112 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700113
Michael Jurka0142d492010-08-25 17:46:15 -0700114 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800115 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700116 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700117 private VelocityTracker mVelocityTracker;
118
Adam Cohen7d30a372013-07-01 17:03:59 -0700119 private float mParentDownMotionX;
120 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700121 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700122 private float mDownMotionY;
123 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700124 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800125 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800126 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800127 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800128 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700129 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700130
131 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700132
Michael Jurka0142d492010-08-25 17:46:15 -0700133 protected final static int TOUCH_STATE_REST = 0;
134 protected final static int TOUCH_STATE_SCROLLING = 1;
135 protected final static int TOUCH_STATE_PREV_PAGE = 2;
136 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700137 protected final static int TOUCH_STATE_REORDERING = 4;
138
Adam Cohene45440e2010-10-14 18:33:38 -0700139 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700140
Michael Jurka0142d492010-08-25 17:46:15 -0700141 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700142 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700143
Michael Jurka0142d492010-08-25 17:46:15 -0700144 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700145
Michael Jurka7426c422010-11-11 15:23:47 -0800146 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700147 private int mPagingTouchSlop;
148 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700149 protected int mPageSpacing;
150 protected int mPageLayoutPaddingTop;
151 protected int mPageLayoutPaddingBottom;
152 protected int mPageLayoutPaddingLeft;
153 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700154 protected int mPageLayoutWidthGap;
155 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700156 protected int mCellCountX = 0;
157 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700158 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800159 protected boolean mAllowOverScroll = true;
160 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800161 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700162 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700163
Michael Jurka8b805b12012-04-18 14:23:14 -0700164 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800165 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
166 // the screens from continuing to translate beyond the normal bounds.
167 protected int mOverScrollX;
168
Michael Jurka5f1c5092010-09-03 14:15:02 -0700169 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700170
Michael Jurka5f1c5092010-09-03 14:15:02 -0700171 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700172
Winson Chung86f77532010-08-24 11:08:22 -0700173 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700174
Michael Jurkae326f182011-11-21 14:05:46 -0800175 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700176
Michael Jurka0142d492010-08-25 17:46:15 -0700177 // If true, syncPages and syncPageItems will be called to refresh pages
178 protected boolean mContentIsRefreshable = true;
179
180 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700181 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700182
183 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
184 // to switch to a new page
185 protected boolean mUsePagingTouchSlop = true;
186
Michael Jurka8b805b12012-04-18 14:23:14 -0700187 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700188 // (SmoothPagedView does this)
189 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700190 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700191
Patrick Dubroy1262e362010-10-06 15:49:50 -0700192 protected boolean mIsPageMoving = false;
193
Winson Chungf0ea4d32011-06-06 14:27:16 -0700194 // All syncs and layout passes are deferred until data is ready.
195 protected boolean mIsDataReady = false;
196
Adam Cohen7d30a372013-07-01 17:03:59 -0700197 protected boolean mAllowLongPress = true;
198
Winson Chungd2be3812013-07-16 11:11:32 -0700199 // Page Indicator
200 private int mPageIndicatorViewId;
201 private PageIndicator mPageIndicator;
Winson Chung007c6982011-06-14 13:27:53 -0700202
Adam Cohen7d30a372013-07-01 17:03:59 -0700203 // The viewport whether the pages are to be contained (the actual view may be larger than the
204 // viewport)
205 private Rect mViewport = new Rect();
206
207 // Reordering
208 // We use the min scale to determine how much to expand the actually PagedView measured
209 // dimensions such that when we are zoomed out, the view is not clipped
210 private int REORDERING_DROP_REPOSITION_DURATION = 200;
211 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
212 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700213 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700214 private float mMinScale = 1f;
215 protected View mDragView;
216 protected AnimatorSet mZoomInOutAnim;
217 private Runnable mSidePageHoverRunnable;
218 private int mSidePageHoverIndex = -1;
219 // This variable's scope is only for the duration of startReordering() and endReordering()
220 private boolean mReorderingStarted = false;
221 // This variable's scope is for the duration of startReordering() and after the zoomIn()
222 // animation after endReordering()
223 private boolean mIsReordering;
224 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
225 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
226 private int mPostReorderingPreZoomInRemainingAnimationCount;
227 private Runnable mPostReorderingPreZoomInRunnable;
228
Adam Cohen7d30a372013-07-01 17:03:59 -0700229 // Convenience/caching
230 private Matrix mTmpInvMatrix = new Matrix();
231 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700232 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700233 private Rect mTmpRect = new Rect();
234 private Rect mAltTmpRect = new Rect();
235
236 // Fling to delete
237 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
238 private float FLING_TO_DELETE_FRICTION = 0.035f;
239 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
240 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
241 protected int mFlingToDeleteThresholdVelocity = -1400;
242 // Drag to delete
243 private boolean mDeferringForDelete = false;
244 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
245 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
246
247 // Drop to delete
248 private View mDeleteDropTarget;
249
250 private boolean mAutoComputePageSpacing = false;
251 private boolean mRecomputePageSpacing = false;
252
253 // Bouncer
254 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700255
Winson Chung86f77532010-08-24 11:08:22 -0700256 public interface PageSwitchListener {
257 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700258 }
259
Winson Chung321e9ee2010-08-09 13:37:56 -0700260 public PagedView(Context context) {
261 this(context, null);
262 }
263
264 public PagedView(Context context, AttributeSet attrs) {
265 this(context, attrs, 0);
266 }
267
268 public PagedView(Context context, AttributeSet attrs, int defStyle) {
269 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700270
Adam Cohen9c4949e2010-10-05 12:27:22 -0700271 TypedArray a = context.obtainStyledAttributes(attrs,
272 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800273 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700274 if (mPageSpacing < 0) {
275 mAutoComputePageSpacing = mRecomputePageSpacing = true;
276 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700277 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800278 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700279 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800280 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700281 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800282 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700283 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800284 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700285 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700286 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700287 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700288 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700289 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700290 a.recycle();
291
Winson Chung321e9ee2010-08-09 13:37:56 -0700292 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700293 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700294 }
295
296 /**
297 * Initializes various states for this workspace.
298 */
Michael Jurka0142d492010-08-25 17:46:15 -0700299 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700300 mDirtyPageContent = new ArrayList<Boolean>();
301 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800302 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700303 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700304 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700305
306 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700307 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700308 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
309 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700310 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800311
Adam Cohen7d30a372013-07-01 17:03:59 -0700312 // Scale the fling-to-delete threshold by the density
313 mFlingToDeleteThresholdVelocity =
314 (int) (mFlingToDeleteThresholdVelocity * mDensity);
315
Adam Cohen265b9a62011-12-07 14:37:18 -0800316 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
317 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
318 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700319 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700320 }
321
Winson Chungd2be3812013-07-16 11:11:32 -0700322 protected void onAttachedToWindow() {
323 // Hook up the page indicator
324 ViewGroup parent = (ViewGroup) getParent();
325 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
326 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
327 mPageIndicator.removeAllMarkers();
Winson Chung82dfe582013-07-26 15:07:49 -0700328
329 ArrayList<Integer> markers = new ArrayList<Integer>();
330 for (int i = 0; i < getChildCount(); ++i) {
331 markers.add(getPageIndicatorMarker(i));
332 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700333
Winson Chung82dfe582013-07-26 15:07:49 -0700334 mPageIndicator.addMarkers(markers);
Adam Cohenf358a4b2013-07-23 16:47:31 -0700335 mPageIndicator.setOnClickListener((Launcher) getContext());
Winson Chungd2be3812013-07-16 11:11:32 -0700336 }
337 }
338
339 protected void onDetachedFromWindow() {
340 // Unhook the page indicator
341 mPageIndicator = null;
342 }
343
Adam Cohen7d30a372013-07-01 17:03:59 -0700344 void setDeleteDropTarget(View v) {
345 mDeleteDropTarget = v;
346 }
347
348 // Convenience methods to map points from self to parent and vice versa
349 float[] mapPointFromViewToParent(View v, float x, float y) {
350 mTmpPoint[0] = x;
351 mTmpPoint[1] = y;
352 v.getMatrix().mapPoints(mTmpPoint);
353 mTmpPoint[0] += v.getLeft();
354 mTmpPoint[1] += v.getTop();
355 return mTmpPoint;
356 }
357 float[] mapPointFromParentToView(View v, float x, float y) {
358 mTmpPoint[0] = x - v.getLeft();
359 mTmpPoint[1] = y - v.getTop();
360 v.getMatrix().invert(mTmpInvMatrix);
361 mTmpInvMatrix.mapPoints(mTmpPoint);
362 return mTmpPoint;
363 }
364
365 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700366 if (mDragView != null) {
367 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
368 (mDragViewBaselineLeft - mDragView.getLeft());
369 float y = mLastMotionY - mDownMotionY;
370 mDragView.setTranslationX(x);
371 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700372
Adam Cohenf358a4b2013-07-23 16:47:31 -0700373 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
374 + x + ", " + y);
375 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700376 }
377
378 public void setMinScale(float f) {
379 mMinScale = f;
380 requestLayout();
381 }
382
383 @Override
384 public void setScaleX(float scaleX) {
385 super.setScaleX(scaleX);
386 if (isReordering(true)) {
387 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
388 mLastMotionX = p[0];
389 mLastMotionY = p[1];
390 updateDragViewTranslationDuringDrag();
391 }
392 }
393
394 // Convenience methods to get the actual width/height of the PagedView (since it is measured
395 // to be larger to account for the minimum possible scale)
396 int getViewportWidth() {
397 return mViewport.width();
398 }
399 int getViewportHeight() {
400 return mViewport.height();
401 }
402
403 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
404 // PagedView both horizontally and vertically
405 int getViewportOffsetX() {
406 return (getMeasuredWidth() - getViewportWidth()) / 2;
407 }
408
409 int getViewportOffsetY() {
410 return (getMeasuredHeight() - getViewportHeight()) / 2;
411 }
412
Adam Cohenedb40762013-07-18 16:45:45 -0700413 PageIndicator getPageIndicator() {
414 return mPageIndicator;
415 }
Winson Chung82dfe582013-07-26 15:07:49 -0700416 protected int getPageIndicatorMarker(int pageIndex) {
417 return R.layout.page_indicator_marker;
418 }
Adam Cohenedb40762013-07-18 16:45:45 -0700419
Winson Chung86f77532010-08-24 11:08:22 -0700420 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
421 mPageSwitchListener = pageSwitchListener;
422 if (mPageSwitchListener != null) {
423 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700424 }
425 }
426
427 /**
Winson Chung52aee602013-01-30 12:01:02 -0800428 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
429 */
430 public boolean isLayoutRtl() {
431 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
432 }
433
434 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700435 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
436 * out pages.
437 */
438 protected void setDataIsReady() {
439 mIsDataReady = true;
440 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700441
Winson Chungf0ea4d32011-06-06 14:27:16 -0700442 protected boolean isDataReady() {
443 return mIsDataReady;
444 }
445
446 /**
Winson Chung86f77532010-08-24 11:08:22 -0700447 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700448 *
Winson Chung86f77532010-08-24 11:08:22 -0700449 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700450 */
Winson Chung86f77532010-08-24 11:08:22 -0700451 int getCurrentPage() {
452 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700453 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700454
Winson Chung360e63f2012-04-27 13:48:05 -0700455 int getNextPage() {
456 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
457 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700458
Winson Chung86f77532010-08-24 11:08:22 -0700459 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700460 return getChildCount();
461 }
462
Winson Chung86f77532010-08-24 11:08:22 -0700463 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700464 return getChildAt(index);
465 }
466
Adam Cohenae4f1552011-10-20 00:15:42 -0700467 protected int indexToPage(int index) {
468 return index;
469 }
470
Winson Chung321e9ee2010-08-09 13:37:56 -0700471 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800472 * Updates the scroll of the current page immediately to its final scroll position. We use this
473 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
474 * the previous tab page.
475 */
476 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700477 // If the current page is invalid, just reset the scroll position to zero
478 int newX = 0;
479 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700480 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700481 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800482 scrollTo(newX, 0);
483 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800484 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800485 }
486
487 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700488 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
489 * ends, {@link #resumeScrolling()} should be called, along with
490 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
491 */
492 void pauseScrolling() {
493 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700494 }
495
496 /**
497 * Enables scrolling again.
498 * @see #pauseScrolling()
499 */
500 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700501 }
502 /**
Winson Chung86f77532010-08-24 11:08:22 -0700503 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700504 */
Winson Chung86f77532010-08-24 11:08:22 -0700505 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800506 if (!mScroller.isFinished()) {
507 mScroller.abortAnimation();
508 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800509 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
510 // the default
511 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800512 return;
513 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700514
Adam Cohene61a9a22013-06-11 15:45:31 -0700515 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700516 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700517 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700518 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800519 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700520 }
521
Winson Chung8c87cd82013-07-23 16:20:10 -0700522 /**
523 * The restore page will be set in place of the current page at the next (likely first)
524 * layout.
525 */
526 void setRestorePage(int restorePage) {
527 mRestorePage = restorePage;
528 }
529
Michael Jurka0142d492010-08-25 17:46:15 -0700530 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700531 if (mPageSwitchListener != null) {
532 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700533 }
Winson Chungd2be3812013-07-16 11:11:32 -0700534
535 // Update the page indicator (when we aren't reordering)
536 if (mPageIndicator != null && !isReordering(false)) {
537 mPageIndicator.setActiveMarker(getNextPage());
538 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700539 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800540 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700541 if (!mIsPageMoving) {
542 mIsPageMoving = true;
543 onPageBeginMoving();
544 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700545 }
546
Michael Jurkace7e05f2011-02-01 22:02:35 -0800547 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700548 if (mIsPageMoving) {
549 mIsPageMoving = false;
550 onPageEndMoving();
551 }
Michael Jurka0142d492010-08-25 17:46:15 -0700552 }
553
Adam Cohen26976d92011-03-22 15:33:33 -0700554 protected boolean isPageMoving() {
555 return mIsPageMoving;
556 }
557
Michael Jurka0142d492010-08-25 17:46:15 -0700558 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700559 protected void onPageBeginMoving() {
560 }
561
562 // a method that subclasses can override to add behavior
563 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700564 }
565
Winson Chung321e9ee2010-08-09 13:37:56 -0700566 /**
Winson Chung86f77532010-08-24 11:08:22 -0700567 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700568 *
569 * @param l The listener used to respond to long clicks.
570 */
571 @Override
572 public void setOnLongClickListener(OnLongClickListener l) {
573 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700574 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700575 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700576 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700577 }
578 }
579
580 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800581 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700582 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800583 }
584
585 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700586 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700587 // In free scroll mode, we clamp the scrollX
588 if (mFreeScroll) {
589 x = Math.min(x, mFreeScrollMaxScrollX);
590 x = Math.max(x, mFreeScrollMinScrollX);
591 }
592
Adam Cohen0ffac432013-07-10 11:19:26 -0700593 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800594 mUnboundedScrollX = x;
595
Adam Cohen0ffac432013-07-10 11:19:26 -0700596 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
597 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
598 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800599 super.scrollTo(0, y);
600 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700601 if (isRtl) {
602 overScroll(x - mMaxScrollX);
603 } else {
604 overScroll(x);
605 }
Adam Cohen68d73932010-11-15 10:50:58 -0800606 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700607 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800608 super.scrollTo(mMaxScrollX, y);
609 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700610 if (isRtl) {
611 overScroll(x);
612 } else {
613 overScroll(x - mMaxScrollX);
614 }
Adam Cohen68d73932010-11-15 10:50:58 -0800615 }
616 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800617 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800618 super.scrollTo(x, y);
619 }
620
Michael Jurka0142d492010-08-25 17:46:15 -0700621 mTouchX = x;
622 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700623
624 // Update the last motion events when scrolling
625 if (isReordering(true)) {
626 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
627 mLastMotionX = p[0];
628 mLastMotionY = p[1];
629 updateDragViewTranslationDuringDrag();
630 }
Michael Jurka0142d492010-08-25 17:46:15 -0700631 }
632
633 // we moved this functionality to a helper function so SmoothPagedView can reuse it
634 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700635 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700636 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700637 if (getScrollX() != mScroller.getCurrX()
638 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700639 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700640 float scaleX = mFreeScroll ? getScaleX() : 1f;
641 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
642 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700643 }
Michael Jurka0142d492010-08-25 17:46:15 -0700644 invalidate();
645 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700646 } else if (mNextPage != INVALID_PAGE) {
647 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700648 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700649 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700650
Winson Chung9c0565f2013-07-19 13:49:06 -0700651 // Load the associated pages if necessary
652 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
653 loadAssociatedPages(mCurrentPage);
654 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
655 }
656
Adam Cohen73aa9752010-11-24 16:26:58 -0800657 // We don't want to trigger a page end moving unless the page has settled
658 // and the user has stopped scrolling
659 if (mTouchState == TOUCH_STATE_REST) {
660 pageEndMoving();
661 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700662
Adam Cohen7d30a372013-07-01 17:03:59 -0700663 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700664 // Notify the user when the page changes
665 AccessibilityManager accessibilityManager = (AccessibilityManager)
666 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
667 if (accessibilityManager.isEnabled()) {
668 AccessibilityEvent ev =
669 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
670 ev.getText().add(getCurrentPageDescription());
671 sendAccessibilityEventUnchecked(ev);
672 }
Michael Jurka0142d492010-08-25 17:46:15 -0700673 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700674 }
Michael Jurka0142d492010-08-25 17:46:15 -0700675 return false;
676 }
677
678 @Override
679 public void computeScroll() {
680 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700681 }
682
Adam Cohen7d30a372013-07-01 17:03:59 -0700683 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
684 return mTopAlignPageWhenShrinkingForBouncer;
685 }
686
Adam Cohen96d30a12013-07-16 18:13:21 -0700687 public static class LayoutParams extends ViewGroup.LayoutParams {
688 public boolean isFullScreenPage = false;
689
690 /**
691 * {@inheritDoc}
692 */
693 public LayoutParams(int width, int height) {
694 super(width, height);
695 }
696
697 public LayoutParams(ViewGroup.LayoutParams source) {
698 super(source);
699 }
700 }
701
702 protected LayoutParams generateDefaultLayoutParams() {
703 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
704 }
705
Adam Cohenedb40762013-07-18 16:45:45 -0700706 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700707 LayoutParams lp = generateDefaultLayoutParams();
708 lp.isFullScreenPage = true;
709 super.addView(page, 0, lp);
710 }
711
Winson Chung321e9ee2010-08-09 13:37:56 -0700712 @Override
713 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700714 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700715 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
716 return;
717 }
718
Adam Cohen7d30a372013-07-01 17:03:59 -0700719 // We measure the dimensions of the PagedView to be larger than the pages so that when we
720 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700721 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
722 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
723 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700724 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700725 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
726 // viewport, we can be at most one and a half screens offset once we scale down
727 DisplayMetrics dm = getResources().getDisplayMetrics();
728 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
729 int parentWidthSize = (int) (1.5f * maxSize);
730 int parentHeightSize = maxSize;
731 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
732 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
733 mViewport.set(0, 0, widthSize, heightSize);
734
735 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
736 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
737 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700738 }
739
Winson Chung8aad6102012-05-11 16:27:49 -0700740 // Return early if we aren't given a proper dimension
741 if (widthSize <= 0 || heightSize <= 0) {
742 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
743 return;
744 }
745
Adam Lesinski6b879f02010-11-04 16:15:23 -0700746 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
747 * of the All apps view on XLarge displays to not take up more space then it needs. Width
748 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
749 * each page to have the same width.
750 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700751 final int verticalPadding = getPaddingTop() + getPaddingBottom();
752 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700753
754 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700755 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700756 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700757 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
758 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
759 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
760 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700761 final int childCount = getChildCount();
762 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700763 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700764 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700765 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
766
767 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700768 int childHeightMode;
769 int childWidth;
770 int childHeight;
771
772 if (!lp.isFullScreenPage) {
773 if (lp.width == LayoutParams.WRAP_CONTENT) {
774 childWidthMode = MeasureSpec.AT_MOST;
775 } else {
776 childWidthMode = MeasureSpec.EXACTLY;
777 }
778
779 if (lp.height == LayoutParams.WRAP_CONTENT) {
780 childHeightMode = MeasureSpec.AT_MOST;
781 } else {
782 childHeightMode = MeasureSpec.EXACTLY;
783 }
784
785 childWidth = widthSize - horizontalPadding;
786 childHeight = heightSize - verticalPadding;
787
Michael Jurka5f1c5092010-09-03 14:15:02 -0700788 } else {
789 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700790 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700791
792 childWidth = getViewportWidth();
793 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700794 }
795
796 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700797 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
798 final int childHeightMeasureSpec =
799 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700800 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700801 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700802 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700803
Winson Chunga128a7b2012-04-30 15:23:15 -0700804 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700805 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700806 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700807 // The gap between pages in the PagedView should be equal to the gap from the page
808 // to the edge of the screen (so it is not visible in the current screen). To
809 // account for unequal padding on each side of the paged view, we take the maximum
810 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700811 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700812 int spacing = Math.max(offset, widthSize - offset -
813 getChildAt(0).getMeasuredWidth());
814 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700815 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700816 }
817 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700818 }
819
Adam Cohen60b07122011-11-14 17:26:06 -0800820 public void setPageSpacing(int pageSpacing) {
821 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700822 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800823 }
824
Winson Chung321e9ee2010-08-09 13:37:56 -0700825 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700826 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700827 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700828 return;
829 }
830
Winson Chung785d2eb2011-04-14 16:08:02 -0700831 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700832 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700833
Adam Cohenedb40762013-07-18 16:45:45 -0700834 int screenWidth = getViewportWidth();
835
Adam Cohen7d30a372013-07-01 17:03:59 -0700836 int offsetX = getViewportOffsetX();
837 int offsetY = getViewportOffsetY();
838
839 // Update the viewport offsets
840 mViewport.offset(offsetX, offsetY);
841
Adam Cohen0ffac432013-07-10 11:19:26 -0700842 final boolean isRtl = isLayoutRtl();
843
844 final int startIndex = isRtl ? childCount - 1 : 0;
845 final int endIndex = isRtl ? -1 : childCount;
846 final int delta = isRtl ? -1 : 1;
847
Adam Cohen7d30a372013-07-01 17:03:59 -0700848 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700849 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
850
851 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
852 mPageScrolls = new int[getChildCount()];
853 }
854
Adam Cohen0ffac432013-07-10 11:19:26 -0700855 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700856
Adam Cohen22f823d2011-09-01 17:22:18 -0700857 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700858 LayoutParams lp = (LayoutParams) child.getLayoutParams();
859 int childTop;
860
861 if (lp.isFullScreenPage) {
862 childTop = offsetY;
863 } else {
864 childTop = offsetY + getPaddingTop();
865 if (mCenterPagesVertically) {
866 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
867 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700868 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700869
Winson Chung321e9ee2010-08-09 13:37:56 -0700870 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700871 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700872 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800873
Winson Chung785d2eb2011-04-14 16:08:02 -0700874 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700875 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800876 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700877
878 // We assume the left and right padding are equal, and hence center the pages
879 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700880 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700881 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
882
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700883 if (i != endIndex - delta) {
884 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
885 childLeft += childWidth + nextScrollOffset;
886 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700887 }
888 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700889
890 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
891 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800892 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700893 setHorizontalScrollBarEnabled(true);
894 mFirstLayout = false;
895 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700896
897 if (childCount > 0) {
898 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700899 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700900 } else {
901 mMaxScrollX = 0;
902 }
903
904 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
905 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700906 if (mRestorePage > -1) {
907 setCurrentPage(mRestorePage);
908 mRestorePage = -1;
909 } else {
910 setCurrentPage(getNextPage());
911 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700912 }
913 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700914
915 if (isReordering(true)) {
916 updateDragViewTranslationDuringDrag();
917 }
Winson Chunge3193b92010-09-10 11:44:42 -0700918 }
919
Adam Cohenf34bab52010-09-30 14:11:56 -0700920 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700921 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
922
923 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700924 for (int i = 0; i < getChildCount(); i++) {
925 View child = getChildAt(i);
926 if (child != null) {
927 float scrollProgress = getScrollProgress(screenCenter, child, i);
928 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800929 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700930 }
931 }
932 invalidate();
933 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700934 }
935
Winson Chunge3193b92010-09-10 11:44:42 -0700936 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700937 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700938 // Update the page indicator, we don't update the page indicator as we
939 // add/remove pages
940 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700941 int pageIndex = indexOfChild(child);
942 mPageIndicator.addMarker(pageIndex, getPageIndicatorMarker(pageIndex));
Winson Chungd2be3812013-07-16 11:11:32 -0700943 }
944
Adam Cohen2591f6a2011-10-25 14:36:40 -0700945 // This ensures that when children are added, they get the correct transforms / alphas
946 // in accordance with any scroll effects.
947 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700948 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700949
Adam Cohen2591f6a2011-10-25 14:36:40 -0700950 invalidate();
951 }
952
Michael Jurka8b805b12012-04-18 14:23:14 -0700953 @Override
954 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700955 mForceScreenScrolled = true;
956 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700957 }
958
Winson Chungd2be3812013-07-16 11:11:32 -0700959 private void removeMarkerForView(int index) {
960 // Update the page indicator, we don't update the page indicator as we
961 // add/remove pages
962 if (mPageIndicator != null && !isReordering(false)) {
963 mPageIndicator.removeMarker(index);
964 }
965 }
966
967 @Override
968 public void removeView(View v) {
969 // XXX: We should find a better way to hook into this before the view
970 // gets removed form its parent...
971 removeMarkerForView(indexOfChild(v));
972 super.removeView(v);
973 }
974 @Override
975 public void removeViewInLayout(View v) {
976 // XXX: We should find a better way to hook into this before the view
977 // gets removed form its parent...
978 removeMarkerForView(indexOfChild(v));
979 super.removeViewInLayout(v);
980 }
981 @Override
982 public void removeViewAt(int index) {
983 // XXX: We should find a better way to hook into this before the view
984 // gets removed form its parent...
985 removeViewAt(index);
986 super.removeViewAt(index);
987 }
988 @Override
989 public void removeAllViewsInLayout() {
990 // Update the page indicator, we don't update the page indicator as we
991 // add/remove pages
992 if (mPageIndicator != null) {
993 mPageIndicator.removeAllMarkers();
994 }
995
996 super.removeAllViewsInLayout();
997 }
998
Adam Cohen73894962011-10-31 13:17:17 -0700999 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001000 if (index < 0 || index > getChildCount() - 1) return 0;
1001
Adam Cohen0ffac432013-07-10 11:19:26 -07001002 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -07001003
Adam Cohenf698c6e2013-07-17 18:44:25 -07001004 if (isRtl) index = getChildCount() - index - 1;
1005 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001006
Adam Cohenf698c6e2013-07-17 18:44:25 -07001007 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001008 }
1009
Adam Cohenf358a4b2013-07-23 16:47:31 -07001010 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001011 range[0] = 0;
1012 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001013 }
1014
Michael Jurkadde558b2011-11-09 22:09:06 -08001015 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001016 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001017 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001018
Michael Jurkac4fb9172010-09-02 17:19:20 -07001019 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001020 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -07001021 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -07001022 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001023
Winson Chungc9ca2982013-07-19 12:07:38 -07001024 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
1025 View currPage = getPageAt(leftScreen);
1026
1027 // Check if the right edge of the page is in the viewport
1028 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Winson Chungc763c4e2013-07-19 13:49:06 -07001029 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001030 if (mTmpIntPoint[0] < 0) {
1031 break;
1032 }
1033 }
1034 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1035 View currPage = getPageAt(rightScreen);
1036
1037 // Check if the left edge of the page is in the viewport
1038 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001039 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001040 if (mTmpIntPoint[0] >= viewportWidth) {
1041 break;
1042 }
1043 }
1044 range[0] = Math.max(0, leftScreen);
1045 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001046 } else {
1047 range[0] = -1;
1048 range[1] = -1;
1049 }
1050 }
1051
Michael Jurka920d7f42012-05-14 16:29:55 -07001052 protected boolean shouldDrawChild(View child) {
1053 return child.getAlpha() > 0;
1054 }
1055
Michael Jurkadde558b2011-11-09 22:09:06 -08001056 @Override
1057 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001058 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001059 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1060 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001061 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001062
1063 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001064 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1065 // set it for the next frame
1066 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001067 screenScrolled(screenCenter);
1068 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001069 }
1070
1071 // Find out which screens are visible; as an optimization we only call draw on them
1072 final int pageCount = getChildCount();
1073 if (pageCount > 0) {
1074 getVisiblePages(mTempVisiblePagesRange);
1075 final int leftScreen = mTempVisiblePagesRange[0];
1076 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001077 if (leftScreen != -1 && rightScreen != -1) {
1078 final long drawingTime = getDrawingTime();
1079 // Clip to the bounds
1080 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001081 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1082 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001083
Adam Cohen7d30a372013-07-01 17:03:59 -07001084 // Draw all the children, leaving the drag view for last
1085 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001086 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001087 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001088 if (mForceDrawAllChildrenNextFrame ||
1089 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001090 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001091 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001092 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001093 // Draw the drag view on top (if there is one)
1094 if (mDragView != null) {
1095 drawChild(canvas, mDragView, drawingTime);
1096 }
1097
Michael Jurka5e368ff2012-05-14 23:13:15 -07001098 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001099 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001100 }
Michael Jurka0142d492010-08-25 17:46:15 -07001101 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001102 }
1103
1104 @Override
1105 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001106 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001107 if (page != mCurrentPage || !mScroller.isFinished()) {
1108 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001109 return true;
1110 }
1111 return false;
1112 }
1113
1114 @Override
1115 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001116 int focusablePage;
1117 if (mNextPage != INVALID_PAGE) {
1118 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001119 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001120 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001121 }
Winson Chung86f77532010-08-24 11:08:22 -07001122 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001123 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001124 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001125 }
1126 return false;
1127 }
1128
1129 @Override
1130 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001131 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001132 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001133 if (getCurrentPage() > 0) {
1134 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001135 return true;
1136 }
1137 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001138 if (getCurrentPage() < getPageCount() - 1) {
1139 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001140 return true;
1141 }
1142 }
1143 return super.dispatchUnhandledMove(focused, direction);
1144 }
1145
1146 @Override
1147 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001148 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001149 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001150 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001151 }
1152 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001153 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001154 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001155 }
1156 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001157 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001158 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001159 }
1160 }
1161 }
1162
1163 /**
1164 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001165 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001166 *
Winson Chung86f77532010-08-24 11:08:22 -07001167 * This happens when live folders requery, and if they're off page, they
1168 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001169 */
1170 @Override
1171 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001172 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001173 View v = focused;
1174 while (true) {
1175 if (v == current) {
1176 super.focusableViewAvailable(focused);
1177 return;
1178 }
1179 if (v == this) {
1180 return;
1181 }
1182 ViewParent parent = v.getParent();
1183 if (parent instanceof View) {
1184 v = (View)v.getParent();
1185 } else {
1186 return;
1187 }
1188 }
1189 }
1190
1191 /**
1192 * {@inheritDoc}
1193 */
1194 @Override
1195 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1196 if (disallowIntercept) {
1197 // We need to make sure to cancel our long press if
1198 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001199 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001200 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001201 }
1202 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1203 }
1204
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001205 /**
1206 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1207 */
1208 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001209 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001210 if (isLayoutRtl()) {
1211 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001212 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001213 }
Adam Cohenedb40762013-07-18 16:45:45 -07001214 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001215 }
1216
1217 /**
1218 * Return true if a tap at (x, y) should trigger a flip to the next page.
1219 */
1220 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001221 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001222 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001223 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001224 }
1225 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001226 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001227 }
Winson Chung52aee602013-01-30 12:01:02 -08001228
Adam Cohen7d30a372013-07-01 17:03:59 -07001229 /** Returns whether x and y originated within the buffered viewport */
1230 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1231 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1232 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1233 return mTmpRect.contains(x, y);
1234 }
1235
Winson Chung321e9ee2010-08-09 13:37:56 -07001236 @Override
1237 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001238 if (DISABLE_TOUCH_INTERACTION) {
1239 return false;
1240 }
1241
Winson Chung321e9ee2010-08-09 13:37:56 -07001242 /*
1243 * This method JUST determines whether we want to intercept the motion.
1244 * If we return true, onTouchEvent will be called and we do the actual
1245 * scrolling there.
1246 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001247 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001248
Winson Chung45e1d6e2010-11-09 17:19:49 -08001249 // Skip touch handling if there are no pages to swipe
1250 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1251
Winson Chung321e9ee2010-08-09 13:37:56 -07001252 /*
1253 * Shortcut the most recurring case: the user is in the dragging
1254 * state and he is moving his finger. We want to intercept this
1255 * motion.
1256 */
1257 final int action = ev.getAction();
1258 if ((action == MotionEvent.ACTION_MOVE) &&
1259 (mTouchState == TOUCH_STATE_SCROLLING)) {
1260 return true;
1261 }
1262
Winson Chung321e9ee2010-08-09 13:37:56 -07001263 switch (action & MotionEvent.ACTION_MASK) {
1264 case MotionEvent.ACTION_MOVE: {
1265 /*
1266 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1267 * whether the user has moved far enough from his original down touch.
1268 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001269 if (mActivePointerId != INVALID_POINTER) {
1270 determineScrollingStart(ev);
1271 break;
1272 }
1273 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1274 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1275 // i.e. fall through to the next case (don't break)
1276 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1277 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001278 }
1279
1280 case MotionEvent.ACTION_DOWN: {
1281 final float x = ev.getX();
1282 final float y = ev.getY();
1283 // Remember location of down touch
1284 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001285 mDownMotionY = y;
1286 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001287 mLastMotionX = x;
1288 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001289 float[] p = mapPointFromViewToParent(this, x, y);
1290 mParentDownMotionX = p[0];
1291 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001292 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001293 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001294 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001295
Winson Chung321e9ee2010-08-09 13:37:56 -07001296 /*
1297 * If being flinged and user touches the screen, initiate drag;
1298 * otherwise don't. mScroller.isFinished should be false when
1299 * being flinged.
1300 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001301 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001302 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1303 if (finishedScrolling) {
1304 mTouchState = TOUCH_STATE_REST;
1305 mScroller.abortAnimation();
1306 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001307 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1308 mTouchState = TOUCH_STATE_SCROLLING;
1309 } else {
1310 mTouchState = TOUCH_STATE_REST;
1311 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001312 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001313
Winson Chung86f77532010-08-24 11:08:22 -07001314 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001315 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001316 if (!DISABLE_TOUCH_SIDE_PAGES) {
1317 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1318 if (getChildCount() > 0) {
1319 if (hitsPreviousPage(x, y)) {
1320 mTouchState = TOUCH_STATE_PREV_PAGE;
1321 } else if (hitsNextPage(x, y)) {
1322 mTouchState = TOUCH_STATE_NEXT_PAGE;
1323 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001324 }
1325 }
1326 }
1327 break;
1328 }
1329
Winson Chung321e9ee2010-08-09 13:37:56 -07001330 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001331 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001332 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001333 break;
1334
1335 case MotionEvent.ACTION_POINTER_UP:
1336 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001337 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001338 break;
1339 }
1340
1341 /*
1342 * The only time we want to intercept motion events is if we are in the
1343 * drag mode.
1344 */
1345 return mTouchState != TOUCH_STATE_REST;
1346 }
1347
Adam Cohenf8d28232011-02-01 21:47:00 -08001348 protected void determineScrollingStart(MotionEvent ev) {
1349 determineScrollingStart(ev, 1.0f);
1350 }
1351
Winson Chung321e9ee2010-08-09 13:37:56 -07001352 /*
1353 * Determines if we should change the touch state to start scrolling after the
1354 * user moves their touch point too far.
1355 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001356 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001357 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001358 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001359 if (pointerIndex == -1) return;
1360
1361 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001362 final float x = ev.getX(pointerIndex);
1363 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001364 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1365
Winson Chung321e9ee2010-08-09 13:37:56 -07001366 final int xDiff = (int) Math.abs(x - mLastMotionX);
1367 final int yDiff = (int) Math.abs(y - mLastMotionY);
1368
Adam Cohenf8d28232011-02-01 21:47:00 -08001369 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001370 boolean xPaged = xDiff > mPagingTouchSlop;
1371 boolean xMoved = xDiff > touchSlop;
1372 boolean yMoved = yDiff > touchSlop;
1373
Adam Cohenf8d28232011-02-01 21:47:00 -08001374 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001375 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001376 // Scroll if the user moved far enough along the X axis
1377 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001378 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001379 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001380 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001381 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001382 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1383 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001384 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001385 }
1386 }
1387
Adam Cohen7d30a372013-07-01 17:03:59 -07001388 protected float getMaxScrollProgress() {
1389 return 1.0f;
1390 }
1391
Adam Cohenf8d28232011-02-01 21:47:00 -08001392 protected void cancelCurrentPageLongPress() {
1393 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001394 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001395 // Try canceling the long press. It could also have been scheduled
1396 // by a distant descendant, so use the mAllowLongPress flag to block
1397 // everything
1398 final View currentPage = getPageAt(mCurrentPage);
1399 if (currentPage != null) {
1400 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001401 }
1402 }
1403 }
1404
Adam Cohen7d30a372013-07-01 17:03:59 -07001405 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1406 final int halfScreenSize = getViewportWidth() / 2;
1407
1408 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1409 screenCenter = Math.max(halfScreenSize, screenCenter);
1410
1411 return getScrollProgress(screenCenter, v, page);
1412 }
1413
Adam Cohenb5ba0972011-09-07 18:02:31 -07001414 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001415 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001416
Adam Cohen96d30a12013-07-16 18:13:21 -07001417 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001418 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001419
1420 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001421 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1422 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001423 return scrollProgress;
1424 }
1425
Adam Cohenedb40762013-07-18 16:45:45 -07001426 public int getScrollForPage(int index) {
1427 if (mPageScrolls == null || index >= mPageScrolls.length) {
1428 return 0;
1429 } else {
1430 return mPageScrolls[index];
1431 }
1432 }
1433
Adam Cohene0f66b52010-11-23 15:06:07 -08001434 // This curve determines how the effect of scrolling over the limits of the page dimishes
1435 // as the user pulls further and further from the bounds
1436 private float overScrollInfluenceCurve(float f) {
1437 f -= 1.0f;
1438 return f * f * f + 1.0f;
1439 }
1440
Adam Cohenb5ba0972011-09-07 18:02:31 -07001441 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001442 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001443
1444 // We want to reach the max over scroll effect when the user has
1445 // over scrolled half the size of the screen
1446 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1447
1448 if (f == 0) return;
1449
1450 // Clamp this factor, f, to -1 < f < 1
1451 if (Math.abs(f) >= 1) {
1452 f /= Math.abs(f);
1453 }
1454
1455 int overScrollAmount = (int) Math.round(f * screenSize);
1456 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001457 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001458 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001459 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001460 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001461 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001462 }
1463 invalidate();
1464 }
1465
1466 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001467 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001468
1469 float f = (amount / screenSize);
1470
1471 if (f == 0) return;
1472 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1473
Adam Cohen7bfc9792011-01-28 13:52:37 -08001474 // Clamp this factor, f, to -1 < f < 1
1475 if (Math.abs(f) >= 1) {
1476 f /= Math.abs(f);
1477 }
1478
Adam Cohene0f66b52010-11-23 15:06:07 -08001479 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001480 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001481 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001482 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001483 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001484 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001485 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001486 }
1487 invalidate();
1488 }
1489
Adam Cohenb5ba0972011-09-07 18:02:31 -07001490 protected void overScroll(float amount) {
1491 dampedOverScroll(amount);
1492 }
1493
Michael Jurkac5b262c2011-01-12 20:24:50 -08001494 protected float maxOverScroll() {
1495 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001496 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001497 float f = 1.0f;
1498 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1499 return OVERSCROLL_DAMP_FACTOR * f;
1500 }
1501
Adam Cohenf358a4b2013-07-23 16:47:31 -07001502 protected void enableFreeScroll() {
1503 setEnableFreeScroll(true, -1);
1504 }
1505
1506 protected void disableFreeScroll(int snapPage) {
1507 setEnableFreeScroll(false, snapPage);
1508 }
1509
1510 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1511 mFreeScroll = freeScroll;
1512
1513 if (snapPage == -1) {
1514 snapPage = getPageNearestToCenterOfScreen();
1515 }
1516
1517 getOverviewModePages(mTempVisiblePagesRange);
1518 if (!mFreeScroll) {
1519 snapToPage(snapPage);
1520
1521 for (int i = 0; i < getPageCount(); ++i) {
1522 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
1523 getPageAt(i).setAlpha(1f);
1524 }
1525 }
1526 } else {
1527 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1528 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1529
1530 for (int i = 0; i < getPageCount(); ++i) {
1531 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
1532 getPageAt(i).setAlpha(0f);
1533 }
1534 }
1535
1536 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1537 setCurrentPage(mTempVisiblePagesRange[0]);
1538 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1539 setCurrentPage(mTempVisiblePagesRange[1]);
1540 }
1541 }
1542
1543 setEnableOverscroll(!freeScroll);
1544 }
1545
1546 private void setEnableOverscroll(boolean enable) {
1547 mAllowOverScroll = enable;
1548 }
1549
1550 int getNearestHoverOverPageIndex() {
1551 if (mDragView != null) {
1552 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1553 + mDragView.getTranslationX());
1554 getOverviewModePages(mTempVisiblePagesRange);
1555 int minDistance = Integer.MAX_VALUE;
1556 int minIndex = indexOfChild(mDragView);
1557 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1558 View page = getPageAt(i);
1559 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1560 int d = Math.abs(dragX - pageX);
1561 if (d < minDistance) {
1562 minIndex = i;
1563 minDistance = d;
1564 }
1565 }
1566 return minIndex;
1567 }
1568 return -1;
1569 }
1570
Winson Chung321e9ee2010-08-09 13:37:56 -07001571 @Override
1572 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001573 if (DISABLE_TOUCH_INTERACTION) {
1574 return false;
1575 }
1576
Winson Chung45e1d6e2010-11-09 17:19:49 -08001577 // Skip touch handling if there are no pages to swipe
1578 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1579
Michael Jurkab8f06722010-10-10 15:58:46 -07001580 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001581
1582 final int action = ev.getAction();
1583
1584 switch (action & MotionEvent.ACTION_MASK) {
1585 case MotionEvent.ACTION_DOWN:
1586 /*
1587 * If being flinged and user touches, stop the fling. isFinished
1588 * will be false if being flinged.
1589 */
1590 if (!mScroller.isFinished()) {
1591 mScroller.abortAnimation();
1592 }
1593
1594 // Remember where the motion event started
1595 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001596 mDownMotionY = mLastMotionY = ev.getY();
1597 mDownScrollX = getScrollX();
1598 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1599 mParentDownMotionX = p[0];
1600 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001601 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001602 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001603 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001604
Michael Jurka0142d492010-08-25 17:46:15 -07001605 if (mTouchState == TOUCH_STATE_SCROLLING) {
1606 pageBeginMoving();
1607 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001608 break;
1609
1610 case MotionEvent.ACTION_MOVE:
1611 if (mTouchState == TOUCH_STATE_SCROLLING) {
1612 // Scroll to follow the motion event
1613 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001614
1615 if (pointerIndex == -1) return true;
1616
Winson Chung321e9ee2010-08-09 13:37:56 -07001617 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001618 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001619
Adam Cohenaefd4e12011-02-14 16:39:38 -08001620 mTotalMotionX += Math.abs(deltaX);
1621
Winson Chungc0844aa2011-02-02 15:25:58 -08001622 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1623 // keep the remainder because we are actually testing if we've moved from the last
1624 // scrolled position (which is discrete).
1625 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001626 mTouchX += deltaX;
1627 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1628 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001629 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001630 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001631 } else {
1632 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001633 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001634 mLastMotionX = x;
1635 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001636 } else {
1637 awakenScrollBars();
1638 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001639 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1640 // Update the last motion position
1641 mLastMotionX = ev.getX();
1642 mLastMotionY = ev.getY();
1643
1644 // Update the parent down so that our zoom animations take this new movement into
1645 // account
1646 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1647 mParentDownMotionX = pt[0];
1648 mParentDownMotionY = pt[1];
1649 updateDragViewTranslationDuringDrag();
1650
1651 // Find the closest page to the touch point
1652 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001653
1654 // Change the drag view if we are hovering over the drop target
1655 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1656 (int) mParentDownMotionX, (int) mParentDownMotionY);
1657 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1658
Adam Cohen7d30a372013-07-01 17:03:59 -07001659 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1660 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1661 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1662 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1663
Adam Cohenf358a4b2013-07-23 16:47:31 -07001664 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1665 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1666 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001667 mTempVisiblePagesRange[0] = 0;
1668 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001669 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001670 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1671 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1672 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1673 mSidePageHoverIndex = pageUnderPointIndex;
1674 mSidePageHoverRunnable = new Runnable() {
1675 @Override
1676 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001677 // Setup the scroll to the correct page before we swap the views
1678 snapToPage(pageUnderPointIndex);
1679
1680 // For each of the pages between the paged view and the drag view,
1681 // animate them from the previous position to the new position in
1682 // the layout (as a result of the drag view moving in the layout)
1683 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1684 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1685 dragViewIndex + 1 : pageUnderPointIndex;
1686 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1687 dragViewIndex - 1 : pageUnderPointIndex;
1688 for (int i = lowerIndex; i <= upperIndex; ++i) {
1689 View v = getChildAt(i);
1690 // dragViewIndex < pageUnderPointIndex, so after we remove the
1691 // drag view all subsequent views to pageUnderPointIndex will
1692 // shift down.
1693 int oldX = getViewportOffsetX() + getChildOffset(i);
1694 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1695
1696 // Animate the view translation from its old position to its new
1697 // position
1698 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1699 if (anim != null) {
1700 anim.cancel();
1701 }
1702
1703 v.setTranslationX(oldX - newX);
1704 anim = new AnimatorSet();
1705 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1706 anim.playTogether(
1707 ObjectAnimator.ofFloat(v, "translationX", 0f));
1708 anim.start();
1709 v.setTag(anim);
1710 }
1711
1712 removeView(mDragView);
1713 onRemoveView(mDragView, false);
1714 addView(mDragView, pageUnderPointIndex);
1715 onAddView(mDragView, pageUnderPointIndex);
1716 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001717 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001718 }
1719 };
1720 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1721 }
1722 } else {
1723 removeCallbacks(mSidePageHoverRunnable);
1724 mSidePageHoverIndex = -1;
1725 }
Adam Cohen564976a2010-10-13 18:52:07 -07001726 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001727 determineScrollingStart(ev);
1728 }
1729 break;
1730
1731 case MotionEvent.ACTION_UP:
1732 if (mTouchState == TOUCH_STATE_SCROLLING) {
1733 final int activePointerId = mActivePointerId;
1734 final int pointerIndex = ev.findPointerIndex(activePointerId);
1735 final float x = ev.getX(pointerIndex);
1736 final VelocityTracker velocityTracker = mVelocityTracker;
1737 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1738 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001739 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001740 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001741 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1742 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001743
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001744 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1745
Adam Cohen00481b32011-11-18 12:03:48 -08001746 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001747 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001748
Adam Cohenf358a4b2013-07-23 16:47:31 -07001749 if (!mFreeScroll) {
1750 // In the case that the page is moved far to one direction and then is flung
1751 // in the opposite direction, we use a threshold to determine whether we should
1752 // just return to the starting page, or if we should skip one further.
1753 boolean returnToOriginalPage = false;
1754 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1755 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1756 returnToOriginalPage = true;
1757 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001758
Adam Cohenf358a4b2013-07-23 16:47:31 -07001759 int finalPage;
1760 // We give flings precedence over large moves, which is why we short-circuit our
1761 // test for a large move if a fling has been registered. That is, a large
1762 // move to the left and fling to the right will register as a fling to the right.
1763 final boolean isRtl = isLayoutRtl();
1764 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1765 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1766 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1767 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1768 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1769 snapToPageWithVelocity(finalPage, velocityX);
1770 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1771 (isFling && isVelocityXLeft)) &&
1772 mCurrentPage < getChildCount() - 1) {
1773 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1774 snapToPageWithVelocity(finalPage, velocityX);
1775 } else {
1776 snapToDestination();
1777 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1778 // at this point we have not moved beyond the touch slop
1779 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1780 // we can just page
1781 int nextPage = Math.max(0, mCurrentPage - 1);
1782 if (nextPage != mCurrentPage) {
1783 snapToPage(nextPage);
1784 } else {
1785 snapToDestination();
1786 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001787 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001788 if (!mScroller.isFinished()) {
1789 mScroller.abortAnimation();
1790 }
1791
1792 float scaleX = getScaleX();
1793 int vX = (int) (-velocityX * scaleX);
1794 int initialScrollX = (int) (getScrollX() * scaleX);
1795
1796 mScroller.fling(initialScrollX,
1797 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1798 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001799 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001800 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001801 // at this point we have not moved beyond the touch slop
1802 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1803 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001804 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1805 if (nextPage != mCurrentPage) {
1806 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001807 } else {
1808 snapToDestination();
1809 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001810 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1811 // Update the last motion position
1812 mLastMotionX = ev.getX();
1813 mLastMotionY = ev.getY();
1814
1815 // Update the parent down so that our zoom animations take this new movement into
1816 // account
1817 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1818 mParentDownMotionX = pt[0];
1819 mParentDownMotionY = pt[1];
1820 updateDragViewTranslationDuringDrag();
1821 boolean handledFling = false;
1822 if (!DISABLE_FLING_TO_DELETE) {
1823 // Check the velocity and see if we are flinging-to-delete
1824 PointF flingToDeleteVector = isFlingingToDelete();
1825 if (flingToDeleteVector != null) {
1826 onFlingToDelete(flingToDeleteVector);
1827 handledFling = true;
1828 }
1829 }
1830 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1831 (int) mParentDownMotionY)) {
1832 onDropToDelete();
1833 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001834 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001835 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001836 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001837
1838 // Remove the callback to wait for the side page hover timeout
1839 removeCallbacks(mSidePageHoverRunnable);
1840 // End any intermediate reordering states
1841 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001842 break;
1843
1844 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001845 if (mTouchState == TOUCH_STATE_SCROLLING) {
1846 snapToDestination();
1847 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001848 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001849 break;
1850
1851 case MotionEvent.ACTION_POINTER_UP:
1852 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001853 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001854 break;
1855 }
1856
1857 return true;
1858 }
1859
Adam Cohen7d30a372013-07-01 17:03:59 -07001860 public void onFlingToDelete(View v) {}
1861 public void onRemoveView(View v, boolean deletePermanently) {}
1862 public void onRemoveViewAnimationCompleted() {}
1863 public void onAddView(View v, int index) {}
1864
1865 private void resetTouchState() {
1866 releaseVelocityTracker();
1867 endReordering();
1868 mTouchState = TOUCH_STATE_REST;
1869 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001870 }
1871
1872 protected void onUnhandledTap(MotionEvent ev) {}
1873
Winson Chung185d7162011-02-28 13:47:29 -08001874 @Override
1875 public boolean onGenericMotionEvent(MotionEvent event) {
1876 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1877 switch (event.getAction()) {
1878 case MotionEvent.ACTION_SCROLL: {
1879 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1880 final float vscroll;
1881 final float hscroll;
1882 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1883 vscroll = 0;
1884 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1885 } else {
1886 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1887 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1888 }
1889 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001890 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1891 : (hscroll > 0 || vscroll > 0);
1892 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001893 scrollRight();
1894 } else {
1895 scrollLeft();
1896 }
1897 return true;
1898 }
1899 }
1900 }
1901 }
1902 return super.onGenericMotionEvent(event);
1903 }
1904
Michael Jurkab8f06722010-10-10 15:58:46 -07001905 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1906 if (mVelocityTracker == null) {
1907 mVelocityTracker = VelocityTracker.obtain();
1908 }
1909 mVelocityTracker.addMovement(ev);
1910 }
1911
1912 private void releaseVelocityTracker() {
1913 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001914 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001915 mVelocityTracker.recycle();
1916 mVelocityTracker = null;
1917 }
1918 }
1919
Winson Chung321e9ee2010-08-09 13:37:56 -07001920 private void onSecondaryPointerUp(MotionEvent ev) {
1921 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1922 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1923 final int pointerId = ev.getPointerId(pointerIndex);
1924 if (pointerId == mActivePointerId) {
1925 // This was our active pointer going up. Choose a new
1926 // active pointer and adjust accordingly.
1927 // TODO: Make this decision more intelligent.
1928 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1929 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1930 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001931 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001932 mActivePointerId = ev.getPointerId(newPointerIndex);
1933 if (mVelocityTracker != null) {
1934 mVelocityTracker.clear();
1935 }
1936 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001937 }
1938
Winson Chung321e9ee2010-08-09 13:37:56 -07001939 @Override
1940 public void requestChildFocus(View child, View focused) {
1941 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001942 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001943 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001944 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001945 }
1946 }
1947
Winson Chung1908d072011-02-24 18:09:44 -08001948 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001949 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001950 }
1951
Adam Cohen7d30a372013-07-01 17:03:59 -07001952 int getPageNearestToPoint(float x) {
1953 int index = 0;
1954 for (int i = 0; i < getChildCount(); ++i) {
1955 if (x < getChildAt(i).getRight() - getScrollX()) {
1956 return index;
1957 } else {
1958 index++;
1959 }
1960 }
1961 return Math.min(index, getChildCount() - 1);
1962 }
1963
Adam Cohend19d3ca2010-09-15 14:43:42 -07001964 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001965 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001966 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001967 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001968 final int childCount = getChildCount();
1969 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001970 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001971 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001972 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001973 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001974 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1975 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1976 minDistanceFromScreenCenter = distanceFromScreenCenter;
1977 minDistanceFromScreenCenterIndex = i;
1978 }
1979 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001980 return minDistanceFromScreenCenterIndex;
1981 }
1982
1983 protected void snapToDestination() {
1984 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001985 }
1986
Adam Cohene0f66b52010-11-23 15:06:07 -08001987 private static class ScrollInterpolator implements Interpolator {
1988 public ScrollInterpolator() {
1989 }
1990
1991 public float getInterpolation(float t) {
1992 t -= 1.0f;
1993 return t*t*t*t*t + 1;
1994 }
1995 }
1996
1997 // We want the duration of the page snap animation to be influenced by the distance that
1998 // the screen has to travel, however, we don't want this duration to be effected in a
1999 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2000 // of travel has on the overall snap duration.
2001 float distanceInfluenceForSnapDuration(float f) {
2002 f -= 0.5f; // center the values about 0.
2003 f *= 0.3f * Math.PI / 2.0f;
2004 return (float) Math.sin(f);
2005 }
2006
Michael Jurka0142d492010-08-25 17:46:15 -07002007 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002008 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002009 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002010
Adam Cohenedb40762013-07-18 16:45:45 -07002011 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002012 int delta = newX - mUnboundedScrollX;
2013 int duration = 0;
2014
Adam Cohen265b9a62011-12-07 14:37:18 -08002015 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002016 // If the velocity is low enough, then treat this more as an automatic page advance
2017 // as opposed to an apparent physical response to flinging
2018 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2019 return;
2020 }
2021
2022 // Here we compute a "distance" that will be used in the computation of the overall
2023 // snap duration. This is a function of the actual distance that needs to be traveled;
2024 // we keep this value close to half screen size in order to reduce the variance in snap
2025 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002026 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002027 float distance = halfScreenSize + halfScreenSize *
2028 distanceInfluenceForSnapDuration(distanceRatio);
2029
2030 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002031 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002032
2033 // we want the page's snap velocity to approximately match the velocity at which the
2034 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002035 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2036 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002037
2038 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002039 }
2040
2041 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002042 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002043 }
2044
Adam Cohen7d30a372013-07-01 17:03:59 -07002045 protected void snapToPageImmediately(int whichPage) {
2046 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2047 }
2048
Michael Jurka0142d492010-08-25 17:46:15 -07002049 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002050 snapToPage(whichPage, duration, false);
2051 }
2052
2053 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002054 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002055
Adam Cohenedb40762013-07-18 16:45:45 -07002056 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002057 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002058 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002059 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002060 }
2061
2062 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002063 snapToPage(whichPage, delta, duration, false);
2064 }
Michael Jurka0142d492010-08-25 17:46:15 -07002065
Adam Cohen7d30a372013-07-01 17:03:59 -07002066 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2067 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002068 View focusedChild = getFocusedChild();
2069 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002070 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002071 focusedChild.clearFocus();
2072 }
2073
2074 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002075 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002076 if (immediate) {
2077 duration = 0;
2078 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002079 duration = Math.abs(delta);
2080 }
2081
Adam Cohenf358a4b2013-07-23 16:47:31 -07002082 if (!mScroller.isFinished()) {
2083 mScroller.abortAnimation();
2084 }
Adam Cohen68d73932010-11-15 10:50:58 -08002085 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002086
Michael Jurka0142d492010-08-25 17:46:15 -07002087 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002088
2089 // Trigger a compute() to finish switching pages if necessary
2090 if (immediate) {
2091 computeScroll();
2092 }
2093
Winson Chung9c0565f2013-07-19 13:49:06 -07002094 // Defer loading associated pages until the scroll settles
2095 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2096
Adam Cohen7d30a372013-07-01 17:03:59 -07002097 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002098 invalidate();
2099 }
2100
Winson Chung321e9ee2010-08-09 13:37:56 -07002101 public void scrollLeft() {
2102 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002103 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002104 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002105 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002106 }
2107 }
2108
2109 public void scrollRight() {
2110 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002111 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002112 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002113 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002114 }
2115 }
2116
Winson Chung86f77532010-08-24 11:08:22 -07002117 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002118 int result = -1;
2119 if (v != null) {
2120 ViewParent vp = v.getParent();
2121 int count = getChildCount();
2122 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002123 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002124 return i;
2125 }
2126 }
2127 }
2128 return result;
2129 }
2130
2131 /**
2132 * @return True is long presses are still allowed for the current touch
2133 */
2134 public boolean allowLongPress() {
2135 return mAllowLongPress;
2136 }
2137
Michael Jurka0142d492010-08-25 17:46:15 -07002138 /**
2139 * Set true to allow long-press events to be triggered, usually checked by
2140 * {@link Launcher} to accept or block dpad-initiated long-presses.
2141 */
2142 public void setAllowLongPress(boolean allowLongPress) {
2143 mAllowLongPress = allowLongPress;
2144 }
2145
Winson Chung321e9ee2010-08-09 13:37:56 -07002146 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002147 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002148
2149 SavedState(Parcelable superState) {
2150 super(superState);
2151 }
2152
2153 private SavedState(Parcel in) {
2154 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002155 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002156 }
2157
2158 @Override
2159 public void writeToParcel(Parcel out, int flags) {
2160 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002161 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002162 }
2163
2164 public static final Parcelable.Creator<SavedState> CREATOR =
2165 new Parcelable.Creator<SavedState>() {
2166 public SavedState createFromParcel(Parcel in) {
2167 return new SavedState(in);
2168 }
2169
2170 public SavedState[] newArray(int size) {
2171 return new SavedState[size];
2172 }
2173 };
2174 }
2175
Winson Chungf314b0e2011-08-16 11:54:27 -07002176 protected void loadAssociatedPages(int page) {
2177 loadAssociatedPages(page, false);
2178 }
2179 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002180 if (mContentIsRefreshable) {
2181 final int count = getChildCount();
2182 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002183 int lowerPageBound = getAssociatedLowerPageBound(page);
2184 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002185 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2186 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002187 // First, clear any pages that should no longer be loaded
2188 for (int i = 0; i < count; ++i) {
2189 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002190 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002191 if (layout.getPageChildCount() > 0) {
2192 layout.removeAllViewsOnPage();
2193 }
2194 mDirtyPageContent.set(i, true);
2195 }
2196 }
2197 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002198 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002199 if ((i != page) && immediateAndOnly) {
2200 continue;
2201 }
Michael Jurka0142d492010-08-25 17:46:15 -07002202 if (lowerPageBound <= i && i <= upperPageBound) {
2203 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002204 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002205 mDirtyPageContent.set(i, false);
2206 }
Winson Chung86f77532010-08-24 11:08:22 -07002207 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002208 }
2209 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002210 }
2211 }
2212
Winson Chunge3193b92010-09-10 11:44:42 -07002213 protected int getAssociatedLowerPageBound(int page) {
2214 return Math.max(0, page - 1);
2215 }
2216 protected int getAssociatedUpperPageBound(int page) {
2217 final int count = getChildCount();
2218 return Math.min(page + 1, count - 1);
2219 }
2220
Winson Chung86f77532010-08-24 11:08:22 -07002221 /**
2222 * This method is called ONLY to synchronize the number of pages that the paged view has.
2223 * To actually fill the pages with information, implement syncPageItems() below. It is
2224 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2225 * and therefore, individual page items do not need to be updated in this method.
2226 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002227 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002228
2229 /**
2230 * This method is called to synchronize the items that are on a particular page. If views on
2231 * the page can be reused, then they should be updated within this method.
2232 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002233 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002234
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002235 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002236 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002237 }
2238 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002239 invalidatePageData(currentPage, false);
2240 }
2241 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002242 if (!mIsDataReady) {
2243 return;
2244 }
2245
Michael Jurka0142d492010-08-25 17:46:15 -07002246 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002247 // Force all scrolling-related behavior to end
2248 mScroller.forceFinished(true);
2249 mNextPage = INVALID_PAGE;
2250
Michael Jurka0142d492010-08-25 17:46:15 -07002251 // Update all the pages
2252 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002253
Winson Chung5a808352011-06-27 19:08:49 -07002254 // We must force a measure after we've loaded the pages to update the content width and
2255 // to determine the full scroll width
2256 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2257 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2258
2259 // Set a new page as the current page if necessary
2260 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002261 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002262 }
2263
Michael Jurka0142d492010-08-25 17:46:15 -07002264 // Mark each of the pages as dirty
2265 final int count = getChildCount();
2266 mDirtyPageContent.clear();
2267 for (int i = 0; i < count; ++i) {
2268 mDirtyPageContent.add(true);
2269 }
2270
2271 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002272 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002273 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002274 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002275 }
Winson Chung007c6982011-06-14 13:27:53 -07002276
Adam Cohen7d30a372013-07-01 17:03:59 -07002277 // Animate the drag view back to the original position
2278 void animateDragViewToOriginalPosition() {
2279 if (mDragView != null) {
2280 AnimatorSet anim = new AnimatorSet();
2281 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2282 anim.playTogether(
2283 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002284 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2285 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2286 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002287 anim.addListener(new AnimatorListenerAdapter() {
2288 @Override
2289 public void onAnimationEnd(Animator animation) {
2290 onPostReorderingAnimationCompleted();
2291 }
2292 });
2293 anim.start();
2294 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002295 }
2296
Adam Cohen7d30a372013-07-01 17:03:59 -07002297 protected void onStartReordering() {
2298 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2299 mTouchState = TOUCH_STATE_REORDERING;
2300 mIsReordering = true;
2301
Adam Cohen7d30a372013-07-01 17:03:59 -07002302 // We must invalidate to trigger a redraw to update the layers such that the drag view
2303 // is always drawn on top
2304 invalidate();
2305 }
2306
2307 private void onPostReorderingAnimationCompleted() {
2308 // Trigger the callback when reordering has settled
2309 --mPostReorderingPreZoomInRemainingAnimationCount;
2310 if (mPostReorderingPreZoomInRunnable != null &&
2311 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2312 mPostReorderingPreZoomInRunnable.run();
2313 mPostReorderingPreZoomInRunnable = null;
2314 }
2315 }
2316
2317 protected void onEndReordering() {
2318 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002319 }
2320
Adam Cohenf358a4b2013-07-23 16:47:31 -07002321 public boolean startReordering(View v) {
2322 int dragViewIndex = indexOfChild(v);//getPageNearestToCenterOfScreen();
Adam Cohen7d30a372013-07-01 17:03:59 -07002323 mTempVisiblePagesRange[0] = 0;
2324 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002325 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002326 mReorderingStarted = true;
2327
2328 // Check if we are within the reordering range
2329 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002330 dragViewIndex <= mTempVisiblePagesRange[1]) {
2331 // Find the drag view under the pointer
2332 mDragView = getChildAt(dragViewIndex);
2333 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2334 mDragViewBaselineLeft = mDragView.getLeft();
2335 disableFreeScroll(-1);
2336 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002337 return true;
2338 }
2339 return false;
2340 }
2341
2342 boolean isReordering(boolean testTouchState) {
2343 boolean state = mIsReordering;
2344 if (testTouchState) {
2345 state &= (mTouchState == TOUCH_STATE_REORDERING);
2346 }
2347 return state;
2348 }
2349 void endReordering() {
2350 // For simplicity, we call endReordering sometimes even if reordering was never started.
2351 // In that case, we don't want to do anything.
2352 if (!mReorderingStarted) return;
2353 mReorderingStarted = false;
2354
2355 // If we haven't flung-to-delete the current child, then we just animate the drag view
2356 // back into position
2357 final Runnable onCompleteRunnable = new Runnable() {
2358 @Override
2359 public void run() {
2360 onEndReordering();
2361 }
2362 };
2363 if (!mDeferringForDelete) {
2364 mPostReorderingPreZoomInRunnable = new Runnable() {
2365 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002366 onCompleteRunnable.run();
2367 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002368 };
2369 };
2370
2371 mPostReorderingPreZoomInRemainingAnimationCount =
2372 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2373 // Snap to the current page
2374 snapToPage(indexOfChild(mDragView), 0);
2375 // Animate the drag view back to the front position
2376 animateDragViewToOriginalPosition();
2377 } else {
2378 // Handled in post-delete-animation-callbacks
2379 }
2380 }
2381
Adam Cohen7d30a372013-07-01 17:03:59 -07002382 /*
2383 * Flinging to delete - IN PROGRESS
2384 */
2385 private PointF isFlingingToDelete() {
2386 ViewConfiguration config = ViewConfiguration.get(getContext());
2387 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2388
2389 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2390 // Do a quick dot product test to ensure that we are flinging upwards
2391 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2392 mVelocityTracker.getYVelocity());
2393 PointF upVec = new PointF(0f, -1f);
2394 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2395 (vel.length() * upVec.length()));
2396 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2397 return vel;
2398 }
2399 }
2400 return null;
2401 }
2402
2403 /**
2404 * Creates an animation from the current drag view along its current velocity vector.
2405 * For this animation, the alpha runs for a fixed duration and we update the position
2406 * progressively.
2407 */
2408 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2409 private View mDragView;
2410 private PointF mVelocity;
2411 private Rect mFrom;
2412 private long mPrevTime;
2413 private float mFriction;
2414
2415 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2416
2417 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2418 long startTime, float friction) {
2419 mDragView = dragView;
2420 mVelocity = vel;
2421 mFrom = from;
2422 mPrevTime = startTime;
2423 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2424 }
2425
2426 @Override
2427 public void onAnimationUpdate(ValueAnimator animation) {
2428 float t = ((Float) animation.getAnimatedValue()).floatValue();
2429 long curTime = AnimationUtils.currentAnimationTimeMillis();
2430
2431 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2432 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2433
2434 mDragView.setTranslationX(mFrom.left);
2435 mDragView.setTranslationY(mFrom.top);
2436 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2437
2438 mVelocity.x *= mFriction;
2439 mVelocity.y *= mFriction;
2440 mPrevTime = curTime;
2441 }
2442 };
2443
2444 private static final int ANIM_TAG_KEY = 100;
2445
2446 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2447 return new Runnable() {
2448 @Override
2449 public void run() {
2450 int dragViewIndex = indexOfChild(dragView);
2451
2452 // For each of the pages around the drag view, animate them from the previous
2453 // position to the new position in the layout (as a result of the drag view moving
2454 // in the layout)
2455 // NOTE: We can make an assumption here because we have side-bound pages that we
2456 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002457 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002458 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2459 boolean slideFromLeft = (isLastWidgetPage ||
2460 dragViewIndex > mTempVisiblePagesRange[0]);
2461
2462 // Setup the scroll to the correct page before we swap the views
2463 if (slideFromLeft) {
2464 snapToPageImmediately(dragViewIndex - 1);
2465 }
2466
2467 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2468 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2469 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2470 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2471 ArrayList<Animator> animations = new ArrayList<Animator>();
2472 for (int i = lowerIndex; i <= upperIndex; ++i) {
2473 View v = getChildAt(i);
2474 // dragViewIndex < pageUnderPointIndex, so after we remove the
2475 // drag view all subsequent views to pageUnderPointIndex will
2476 // shift down.
2477 int oldX = 0;
2478 int newX = 0;
2479 if (slideFromLeft) {
2480 if (i == 0) {
2481 // Simulate the page being offscreen with the page spacing
2482 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2483 - mPageSpacing;
2484 } else {
2485 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2486 }
2487 newX = getViewportOffsetX() + getChildOffset(i);
2488 } else {
2489 oldX = getChildOffset(i) - getChildOffset(i - 1);
2490 newX = 0;
2491 }
2492
2493 // Animate the view translation from its old position to its new
2494 // position
2495 AnimatorSet anim = (AnimatorSet) v.getTag();
2496 if (anim != null) {
2497 anim.cancel();
2498 }
2499
2500 // Note: Hacky, but we want to skip any optimizations to not draw completely
2501 // hidden views
2502 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2503 v.setTranslationX(oldX - newX);
2504 anim = new AnimatorSet();
2505 anim.playTogether(
2506 ObjectAnimator.ofFloat(v, "translationX", 0f),
2507 ObjectAnimator.ofFloat(v, "alpha", 1f));
2508 animations.add(anim);
2509 v.setTag(ANIM_TAG_KEY, anim);
2510 }
2511
2512 AnimatorSet slideAnimations = new AnimatorSet();
2513 slideAnimations.playTogether(animations);
2514 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2515 slideAnimations.addListener(new AnimatorListenerAdapter() {
2516 @Override
2517 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002518 mDeferringForDelete = false;
2519 onEndReordering();
2520 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002521 }
2522 });
2523 slideAnimations.start();
2524
2525 removeView(dragView);
2526 onRemoveView(dragView, true);
2527 }
2528 };
2529 }
2530
2531 public void onFlingToDelete(PointF vel) {
2532 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2533
2534 // NOTE: Because it takes time for the first frame of animation to actually be
2535 // called and we expect the animation to be a continuation of the fling, we have
2536 // to account for the time that has elapsed since the fling finished. And since
2537 // we don't have a startDelay, we will always get call to update when we call
2538 // start() (which we want to ignore).
2539 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2540 private int mCount = -1;
2541 private long mStartTime;
2542 private float mOffset;
2543 /* Anonymous inner class ctor */ {
2544 mStartTime = startTime;
2545 }
2546
2547 @Override
2548 public float getInterpolation(float t) {
2549 if (mCount < 0) {
2550 mCount++;
2551 } else if (mCount == 0) {
2552 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2553 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2554 mCount++;
2555 }
2556 return Math.min(1f, mOffset + t);
2557 }
2558 };
2559
2560 final Rect from = new Rect();
2561 final View dragView = mDragView;
2562 from.left = (int) dragView.getTranslationX();
2563 from.top = (int) dragView.getTranslationY();
2564 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2565 from, startTime, FLING_TO_DELETE_FRICTION);
2566
2567 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2568
2569 // Create and start the animation
2570 ValueAnimator mDropAnim = new ValueAnimator();
2571 mDropAnim.setInterpolator(tInterpolator);
2572 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2573 mDropAnim.setFloatValues(0f, 1f);
2574 mDropAnim.addUpdateListener(updateCb);
2575 mDropAnim.addListener(new AnimatorListenerAdapter() {
2576 public void onAnimationEnd(Animator animation) {
2577 onAnimationEndRunnable.run();
2578 }
2579 });
2580 mDropAnim.start();
2581 mDeferringForDelete = true;
2582 }
2583
2584 /* Drag to delete */
2585 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2586 if (mDeleteDropTarget != null) {
2587 mAltTmpRect.set(0, 0, 0, 0);
2588 View parent = (View) mDeleteDropTarget.getParent();
2589 if (parent != null) {
2590 parent.getGlobalVisibleRect(mAltTmpRect);
2591 }
2592 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2593 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2594 return mTmpRect.contains(x, y);
2595 }
2596 return false;
2597 }
2598
2599 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2600
2601 private void onDropToDelete() {
2602 final View dragView = mDragView;
2603
2604 final float toScale = 0f;
2605 final float toAlpha = 0f;
2606
2607 // Create and start the complex animation
2608 ArrayList<Animator> animations = new ArrayList<Animator>();
2609 AnimatorSet motionAnim = new AnimatorSet();
2610 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2611 motionAnim.playTogether(
2612 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2613 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2614 animations.add(motionAnim);
2615
2616 AnimatorSet alphaAnim = new AnimatorSet();
2617 alphaAnim.setInterpolator(new LinearInterpolator());
2618 alphaAnim.playTogether(
2619 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2620 animations.add(alphaAnim);
2621
2622 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2623
2624 AnimatorSet anim = new AnimatorSet();
2625 anim.playTogether(animations);
2626 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2627 anim.addListener(new AnimatorListenerAdapter() {
2628 public void onAnimationEnd(Animator animation) {
2629 onAnimationEndRunnable.run();
2630 }
2631 });
2632 anim.start();
2633
2634 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002635 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002636
2637 /* Accessibility */
2638 @Override
2639 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2640 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002641 info.setScrollable(getPageCount() > 1);
2642 if (getCurrentPage() < getPageCount() - 1) {
2643 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2644 }
2645 if (getCurrentPage() > 0) {
2646 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2647 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002648 }
2649
2650 @Override
2651 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2652 super.onInitializeAccessibilityEvent(event);
2653 event.setScrollable(true);
2654 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2655 event.setFromIndex(mCurrentPage);
2656 event.setToIndex(mCurrentPage);
2657 event.setItemCount(getChildCount());
2658 }
2659 }
2660
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002661 @Override
2662 public boolean performAccessibilityAction(int action, Bundle arguments) {
2663 if (super.performAccessibilityAction(action, arguments)) {
2664 return true;
2665 }
2666 switch (action) {
2667 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2668 if (getCurrentPage() < getPageCount() - 1) {
2669 scrollRight();
2670 return true;
2671 }
2672 } break;
2673 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2674 if (getCurrentPage() > 0) {
2675 scrollLeft();
2676 return true;
2677 }
2678 } break;
2679 }
2680 return false;
2681 }
2682
Adam Cohen0ffac432013-07-10 11:19:26 -07002683 protected String getCurrentPageDescription() {
2684 return String.format(getContext().getString(R.string.default_scroll_format),
2685 getNextPage() + 1, getChildCount());
2686 }
2687
Winson Chungd11265e2011-08-30 13:37:23 -07002688 @Override
2689 public boolean onHoverEvent(android.view.MotionEvent event) {
2690 return true;
2691 }
Adam Cohenf358a4b2013-07-23 16:47:31 -07002692}