blob: 5052a59760f555a971763c018b02a5274b243bf6 [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
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
17package com.android.launcher2;
18
19import java.util.ArrayList;
Winson Chung86f77532010-08-24 11:08:22 -070020import java.util.Arrays;
Winson Chung241c3b42010-08-25 16:53:03 -070021import java.util.HashMap;
Winson Chung321e9ee2010-08-09 13:37:56 -070022
23import android.content.Context;
Winson Chung241c3b42010-08-25 16:53:03 -070024import android.graphics.Bitmap;
Winson Chung321e9ee2010-08-09 13:37:56 -070025import android.graphics.Canvas;
26import android.graphics.Rect;
Winson Chung321e9ee2010-08-09 13:37:56 -070027import android.os.Parcel;
28import android.os.Parcelable;
29import android.util.AttributeSet;
Winson Chung321e9ee2010-08-09 13:37:56 -070030import android.view.MotionEvent;
31import android.view.VelocityTracker;
32import android.view.View;
33import android.view.ViewConfiguration;
34import android.view.ViewGroup;
35import android.view.ViewParent;
Winson Chung80baf5a2010-08-09 16:03:15 -070036import android.view.animation.Animation;
Winson Chung80baf5a2010-08-09 16:03:15 -070037import android.view.animation.Animation.AnimationListener;
Winson Chung86f77532010-08-24 11:08:22 -070038import android.view.animation.AnimationUtils;
Winson Chung321e9ee2010-08-09 13:37:56 -070039import android.widget.Scroller;
40
Winson Chung80baf5a2010-08-09 16:03:15 -070041import com.android.launcher.R;
42
Winson Chung321e9ee2010-08-09 13:37:56 -070043/**
44 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070045 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070046 */
47public abstract class PagedView extends ViewGroup {
48 private static final String TAG = "PagedView";
Michael Jurka0142d492010-08-25 17:46:15 -070049 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070050
Winson Chung86f77532010-08-24 11:08:22 -070051 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung321e9ee2010-08-09 13:37:56 -070052 private static final int MIN_LENGTH_FOR_FLING = 50;
53
Michael Jurka0142d492010-08-25 17:46:15 -070054 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070055
Michael Jurka0142d492010-08-25 17:46:15 -070056 // the velocity at which a fling gesture will cause us to snap to the next page
57 protected int mSnapVelocity = 500;
58
59 protected float mSmoothingTime;
60 protected float mTouchX;
61
62 protected boolean mFirstLayout = true;
63
64 protected int mCurrentPage;
65 protected int mNextPage = INVALID_PAGE;
66 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -070067 private VelocityTracker mVelocityTracker;
68
69 private float mDownMotionX;
70 private float mLastMotionX;
71 private float mLastMotionY;
72
Michael Jurka0142d492010-08-25 17:46:15 -070073 protected final static int TOUCH_STATE_REST = 0;
74 protected final static int TOUCH_STATE_SCROLLING = 1;
75 protected final static int TOUCH_STATE_PREV_PAGE = 2;
76 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Winson Chung321e9ee2010-08-09 13:37:56 -070077
Michael Jurka0142d492010-08-25 17:46:15 -070078 protected int mTouchState = TOUCH_STATE_REST;
Winson Chung321e9ee2010-08-09 13:37:56 -070079
Michael Jurka0142d492010-08-25 17:46:15 -070080 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070081
82 private boolean mAllowLongPress = true;
83
84 private int mTouchSlop;
85 private int mPagingTouchSlop;
86 private int mMaximumVelocity;
87
88 private static final int INVALID_POINTER = -1;
89
90 private int mActivePointerId = INVALID_POINTER;
91
Michael Jurka0142d492010-08-25 17:46:15 -070092 private enum PageMovingState { PAGE_BEGIN_MOVING, PAGE_END_MOVING };
Winson Chung86f77532010-08-24 11:08:22 -070093 private PageSwitchListener mPageSwitchListener;
Michael Jurka0142d492010-08-25 17:46:15 -070094 private PageMovingListener mPageMovingListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070095
Winson Chung86f77532010-08-24 11:08:22 -070096 private ArrayList<Boolean> mDirtyPageContent;
97 private boolean mDirtyPageAlpha;
Winson Chung321e9ee2010-08-09 13:37:56 -070098
Winson Chung241c3b42010-08-25 16:53:03 -070099 protected PagedViewIconCache mPageViewIconCache;
100
Michael Jurka0142d492010-08-25 17:46:15 -0700101 // If true, syncPages and syncPageItems will be called to refresh pages
102 protected boolean mContentIsRefreshable = true;
103
104 // If true, modify alpha of neighboring pages as user scrolls left/right
105 protected boolean mFadeInAdjacentScreens = true;
106
107 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
108 // to switch to a new page
109 protected boolean mUsePagingTouchSlop = true;
110
111 // If true, the subclass should directly update mScrollX itself in its computeScroll method
112 // (SmoothPagedView does this)
113 protected boolean mDeferScrollUpdate = false;
114
Winson Chung241c3b42010-08-25 16:53:03 -0700115 /**
116 * Simple cache mechanism for PagedViewIcon outlines.
117 */
118 class PagedViewIconCache {
119 private final HashMap<Object, Bitmap> iconOutlineCache = new HashMap<Object, Bitmap>();
120
121 public void clear() {
122 iconOutlineCache.clear();
123 }
124 public void addOutline(Object key, Bitmap b) {
125 iconOutlineCache.put(key, b);
126 }
127 public void removeOutline(Object key) {
128 if (iconOutlineCache.containsKey(key)) {
129 iconOutlineCache.remove(key);
130 }
131 }
132 public Bitmap getOutline(Object key) {
133 return iconOutlineCache.get(key);
134 }
135 }
136
Winson Chung86f77532010-08-24 11:08:22 -0700137 public interface PageSwitchListener {
138 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700139 }
140
Michael Jurka0142d492010-08-25 17:46:15 -0700141 public interface PageMovingListener {
142 void onPageBeginMoving();
143 void onPageEndMoving();
144 }
145
Winson Chung321e9ee2010-08-09 13:37:56 -0700146 public PagedView(Context context) {
147 this(context, null);
148 }
149
150 public PagedView(Context context, AttributeSet attrs) {
151 this(context, attrs, 0);
152 }
153
154 public PagedView(Context context, AttributeSet attrs, int defStyle) {
155 super(context, attrs, defStyle);
156
157 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700158 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700159 }
160
161 /**
162 * Initializes various states for this workspace.
163 */
Michael Jurka0142d492010-08-25 17:46:15 -0700164 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700165 mDirtyPageContent = new ArrayList<Boolean>();
166 mDirtyPageContent.ensureCapacity(32);
Winson Chung241c3b42010-08-25 16:53:03 -0700167 mPageViewIconCache = new PagedViewIconCache();
Winson Chung321e9ee2010-08-09 13:37:56 -0700168 mScroller = new Scroller(getContext());
Winson Chung86f77532010-08-24 11:08:22 -0700169 mCurrentPage = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -0700170
171 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
172 mTouchSlop = configuration.getScaledTouchSlop();
173 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
174 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
175 }
176
Winson Chung86f77532010-08-24 11:08:22 -0700177 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
178 mPageSwitchListener = pageSwitchListener;
179 if (mPageSwitchListener != null) {
180 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700181 }
182 }
183
184 /**
Winson Chung86f77532010-08-24 11:08:22 -0700185 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700186 *
Winson Chung86f77532010-08-24 11:08:22 -0700187 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700188 */
Winson Chung86f77532010-08-24 11:08:22 -0700189 int getCurrentPage() {
190 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700191 }
192
Winson Chung86f77532010-08-24 11:08:22 -0700193 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700194 return getChildCount();
195 }
196
Winson Chung86f77532010-08-24 11:08:22 -0700197 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700198 return getChildAt(index);
199 }
200
201 int getScrollWidth() {
202 return getWidth();
203 }
204
205 /**
Winson Chung86f77532010-08-24 11:08:22 -0700206 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700207 */
Winson Chung86f77532010-08-24 11:08:22 -0700208 void setCurrentPage(int currentPage) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700209 if (!mScroller.isFinished()) mScroller.abortAnimation();
210 if (getChildCount() == 0) return;
211
Winson Chung86f77532010-08-24 11:08:22 -0700212 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
213 scrollTo(getChildOffset(mCurrentPage) - getRelativeChildOffset(mCurrentPage), 0);
Winson Chung80baf5a2010-08-09 16:03:15 -0700214
Winson Chung321e9ee2010-08-09 13:37:56 -0700215 invalidate();
Winson Chung86f77532010-08-24 11:08:22 -0700216 notifyPageSwitchListener();
Winson Chung321e9ee2010-08-09 13:37:56 -0700217 }
218
Michael Jurka0142d492010-08-25 17:46:15 -0700219 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700220 if (mPageSwitchListener != null) {
221 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700222 }
223 }
224
Michael Jurka0142d492010-08-25 17:46:15 -0700225 // a method that subclasses can override to add behavior
226 protected void pageBeginMoving() {
227 }
228
229 // a method that subclasses can override to add behavior
230 protected void pageEndMoving() {
231 }
232
Winson Chung321e9ee2010-08-09 13:37:56 -0700233 /**
Winson Chung86f77532010-08-24 11:08:22 -0700234 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700235 *
236 * @param l The listener used to respond to long clicks.
237 */
238 @Override
239 public void setOnLongClickListener(OnLongClickListener l) {
240 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700241 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700242 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700243 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700244 }
245 }
246
247 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700248 public void scrollTo(int x, int y) {
249 super.scrollTo(x, y);
250 mTouchX = x;
251 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
252 }
253
254 // we moved this functionality to a helper function so SmoothPagedView can reuse it
255 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700256 if (mScroller.computeScrollOffset()) {
257 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
Michael Jurka0142d492010-08-25 17:46:15 -0700258 invalidate();
259 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700260 } else if (mNextPage != INVALID_PAGE) {
261 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700262 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700263 notifyPageSwitchListener();
264 pageEndMoving();
265 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700266 }
Michael Jurka0142d492010-08-25 17:46:15 -0700267 return false;
268 }
269
270 @Override
271 public void computeScroll() {
272 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700273 }
274
275 @Override
276 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
277 final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
278 final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
279 if (widthMode != MeasureSpec.EXACTLY) {
280 throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
281 }
282
283 final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
284 final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
285 if (heightMode != MeasureSpec.EXACTLY) {
286 throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
287 }
288
289 // The children are given the same width and height as the workspace
290 final int childCount = getChildCount();
291 for (int i = 0; i < childCount; i++) {
292 getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
293 }
294
295 setMeasuredDimension(widthSize, heightSize);
296
297 if (mFirstLayout) {
298 setHorizontalScrollBarEnabled(false);
Winson Chung86f77532010-08-24 11:08:22 -0700299 scrollTo(mCurrentPage * widthSize, 0);
Michael Jurka0142d492010-08-25 17:46:15 -0700300 mScroller.setFinalX(mCurrentPage * widthSize);
Winson Chung321e9ee2010-08-09 13:37:56 -0700301 setHorizontalScrollBarEnabled(true);
302 mFirstLayout = false;
303 }
304 }
305
306 @Override
307 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
308 final int childCount = getChildCount();
309 int childLeft = 0;
310 if (childCount > 0) {
311 childLeft = (getMeasuredWidth() - getChildAt(0).getMeasuredWidth()) / 2;
312 }
313
314 for (int i = 0; i < childCount; i++) {
315 final View child = getChildAt(i);
316 if (child.getVisibility() != View.GONE) {
317 final int childWidth = child.getMeasuredWidth();
318 child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight());
319 childLeft += childWidth;
320 }
321 }
322 }
323
Winson Chung321e9ee2010-08-09 13:37:56 -0700324 @Override
325 protected void dispatchDraw(Canvas canvas) {
Michael Jurka0142d492010-08-25 17:46:15 -0700326 if (mFadeInAdjacentScreens) {
327 if (mDirtyPageAlpha || (mTouchState == TOUCH_STATE_SCROLLING) || !mScroller.isFinished()) {
328 int screenCenter = mScrollX + (getMeasuredWidth() / 2);
329 final int childCount = getChildCount();
330 for (int i = 0; i < childCount; ++i) {
331 View layout = (View) getChildAt(i);
332 int childWidth = layout.getMeasuredWidth();
333 int halfChildWidth = (childWidth / 2);
334 int childCenter = getChildOffset(i) + halfChildWidth;
335 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
336 float alpha = 0.0f;
337 if (distanceFromScreenCenter < halfChildWidth) {
338 alpha = 1.0f;
339 } else if (distanceFromScreenCenter > childWidth) {
340 alpha = 0.0f;
341 } else {
342 float dimAlpha = (float) (distanceFromScreenCenter - halfChildWidth) / halfChildWidth;
343 dimAlpha = Math.max(0.0f, Math.min(1.0f, (dimAlpha * dimAlpha)));
344 alpha = 1.0f - dimAlpha;
345 }
346 if (Float.compare(alpha, layout.getAlpha()) != 0) {
347 layout.setAlpha(alpha);
348 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700349 }
Michael Jurka0142d492010-08-25 17:46:15 -0700350 mDirtyPageAlpha = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700351 }
352 }
Michael Jurka0142d492010-08-25 17:46:15 -0700353
354 // Find out which screens are visible; as an optimization we only call draw on them
355
356 // As an optimization, this code assumes that all pages have the same width as the 0th
357 // page.
358 final int pageWidth = getChildAt(0).getMeasuredWidth();
359 final int pageCount = getChildCount();
360 final int screenWidth = getMeasuredWidth();
361 int x = getRelativeChildOffset(0) + pageWidth;
362 int leftScreen = 0;
363 int rightScreen = 0;
364 while (x <= mScrollX) {
365 leftScreen++;
366 x += pageWidth;
367 // replace above line with this if you don't assume all pages have same width as 0th
368 // page:
369 // x += getChildAt(leftScreen).getMeasuredWidth();
370 }
371 rightScreen = leftScreen;
372 while (x < mScrollX + screenWidth) {
373 rightScreen++;
374 x += pageWidth;
375 // replace above line with this if you don't assume all pages have same width as 0th
376 // page:
377 //if (rightScreen < pageCount) {
378 // x += getChildAt(rightScreen).getMeasuredWidth();
379 //}
380 }
381 rightScreen = Math.min(getChildCount() - 1, rightScreen);
382
383 final long drawingTime = getDrawingTime();
384 for (int i = leftScreen; i <= rightScreen; i++) {
385 drawChild(canvas, getChildAt(i), drawingTime);
386 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700387 }
388
389 @Override
390 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -0700391 int page = indexOfChild(child);
392 if (page != mCurrentPage || !mScroller.isFinished()) {
393 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -0700394 return true;
395 }
396 return false;
397 }
398
399 @Override
400 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -0700401 int focusablePage;
402 if (mNextPage != INVALID_PAGE) {
403 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700404 } else {
Winson Chung86f77532010-08-24 11:08:22 -0700405 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700406 }
Winson Chung86f77532010-08-24 11:08:22 -0700407 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700408 if (v != null) {
409 v.requestFocus(direction, previouslyFocusedRect);
410 }
411 return false;
412 }
413
414 @Override
415 public boolean dispatchUnhandledMove(View focused, int direction) {
416 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -0700417 if (getCurrentPage() > 0) {
418 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -0700419 return true;
420 }
421 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -0700422 if (getCurrentPage() < getPageCount() - 1) {
423 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -0700424 return true;
425 }
426 }
427 return super.dispatchUnhandledMove(focused, direction);
428 }
429
430 @Override
431 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Winson Chung86f77532010-08-24 11:08:22 -0700432 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
433 getPageAt(mCurrentPage).addFocusables(views, direction);
Winson Chung321e9ee2010-08-09 13:37:56 -0700434 }
435 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -0700436 if (mCurrentPage > 0) {
437 getPageAt(mCurrentPage - 1).addFocusables(views, direction);
Winson Chung321e9ee2010-08-09 13:37:56 -0700438 }
439 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -0700440 if (mCurrentPage < getPageCount() - 1) {
441 getPageAt(mCurrentPage + 1).addFocusables(views, direction);
Winson Chung321e9ee2010-08-09 13:37:56 -0700442 }
443 }
444 }
445
446 /**
447 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -0700448 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700449 *
Winson Chung86f77532010-08-24 11:08:22 -0700450 * This happens when live folders requery, and if they're off page, they
451 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700452 */
453 @Override
454 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -0700455 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700456 View v = focused;
457 while (true) {
458 if (v == current) {
459 super.focusableViewAvailable(focused);
460 return;
461 }
462 if (v == this) {
463 return;
464 }
465 ViewParent parent = v.getParent();
466 if (parent instanceof View) {
467 v = (View)v.getParent();
468 } else {
469 return;
470 }
471 }
472 }
473
474 /**
475 * {@inheritDoc}
476 */
477 @Override
478 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
479 if (disallowIntercept) {
480 // We need to make sure to cancel our long press if
481 // a scrollable widget takes over touch events
Winson Chung86f77532010-08-24 11:08:22 -0700482 final View currentPage = getChildAt(mCurrentPage);
483 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -0700484 }
485 super.requestDisallowInterceptTouchEvent(disallowIntercept);
486 }
487
488 @Override
489 public boolean onInterceptTouchEvent(MotionEvent ev) {
490 /*
491 * This method JUST determines whether we want to intercept the motion.
492 * If we return true, onTouchEvent will be called and we do the actual
493 * scrolling there.
494 */
495
496 /*
497 * Shortcut the most recurring case: the user is in the dragging
498 * state and he is moving his finger. We want to intercept this
499 * motion.
500 */
501 final int action = ev.getAction();
502 if ((action == MotionEvent.ACTION_MOVE) &&
503 (mTouchState == TOUCH_STATE_SCROLLING)) {
504 return true;
505 }
506
507
508 switch (action & MotionEvent.ACTION_MASK) {
509 case MotionEvent.ACTION_MOVE: {
510 /*
511 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
512 * whether the user has moved far enough from his original down touch.
513 */
514 determineScrollingStart(ev);
515 break;
516 }
517
518 case MotionEvent.ACTION_DOWN: {
519 final float x = ev.getX();
520 final float y = ev.getY();
521 // Remember location of down touch
522 mDownMotionX = x;
523 mLastMotionX = x;
524 mLastMotionY = y;
525 mActivePointerId = ev.getPointerId(0);
526 mAllowLongPress = true;
527
528 /*
529 * If being flinged and user touches the screen, initiate drag;
530 * otherwise don't. mScroller.isFinished should be false when
531 * being flinged.
532 */
533 mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
534
Winson Chung86f77532010-08-24 11:08:22 -0700535 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -0700536 // to scroll the current page
537 if ((mTouchState != TOUCH_STATE_PREV_PAGE) &&
538 (mTouchState != TOUCH_STATE_NEXT_PAGE)) {
539 if (getChildCount() > 0) {
540 int relativeChildLeft = getChildOffset(0);
541 int relativeChildRight = relativeChildLeft + getChildAt(0).getMeasuredWidth();
542 if (x < relativeChildLeft) {
543 mTouchState = TOUCH_STATE_PREV_PAGE;
544 } else if (x > relativeChildRight) {
545 mTouchState = TOUCH_STATE_NEXT_PAGE;
546 }
547 }
548 }
549 break;
550 }
551
552 case MotionEvent.ACTION_CANCEL:
553 case MotionEvent.ACTION_UP:
554 // Release the drag
Michael Jurka0142d492010-08-25 17:46:15 -0700555 pageEndMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -0700556 mTouchState = TOUCH_STATE_REST;
557 mAllowLongPress = false;
558 mActivePointerId = INVALID_POINTER;
559
560 break;
561
562 case MotionEvent.ACTION_POINTER_UP:
563 onSecondaryPointerUp(ev);
564 break;
565 }
566
567 /*
568 * The only time we want to intercept motion events is if we are in the
569 * drag mode.
570 */
571 return mTouchState != TOUCH_STATE_REST;
572 }
573
Winson Chung80baf5a2010-08-09 16:03:15 -0700574 protected void animateClickFeedback(View v, final Runnable r) {
575 // animate the view slightly to show click feedback running some logic after it is "pressed"
576 Animation anim = AnimationUtils.loadAnimation(getContext(),
577 R.anim.paged_view_click_feedback);
578 anim.setAnimationListener(new AnimationListener() {
579 @Override
580 public void onAnimationStart(Animation animation) {}
581 @Override
582 public void onAnimationRepeat(Animation animation) {
583 r.run();
584 }
585 @Override
586 public void onAnimationEnd(Animation animation) {}
587 });
588 v.startAnimation(anim);
589 }
590
Winson Chung321e9ee2010-08-09 13:37:56 -0700591 /*
592 * Determines if we should change the touch state to start scrolling after the
593 * user moves their touch point too far.
594 */
595 private void determineScrollingStart(MotionEvent ev) {
596 /*
597 * Locally do absolute value. mLastMotionX is set to the y value
598 * of the down event.
599 */
600 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
601 final float x = ev.getX(pointerIndex);
602 final float y = ev.getY(pointerIndex);
603 final int xDiff = (int) Math.abs(x - mLastMotionX);
604 final int yDiff = (int) Math.abs(y - mLastMotionY);
605
606 final int touchSlop = mTouchSlop;
607 boolean xPaged = xDiff > mPagingTouchSlop;
608 boolean xMoved = xDiff > touchSlop;
609 boolean yMoved = yDiff > touchSlop;
610
611 if (xMoved || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -0700612 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700613 // Scroll if the user moved far enough along the X axis
614 mTouchState = TOUCH_STATE_SCROLLING;
615 mLastMotionX = x;
Michael Jurka0142d492010-08-25 17:46:15 -0700616 mTouchX = mScrollX;
617 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
618 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -0700619 }
620 // Either way, cancel any pending longpress
621 if (mAllowLongPress) {
622 mAllowLongPress = false;
623 // Try canceling the long press. It could also have been scheduled
624 // by a distant descendant, so use the mAllowLongPress flag to block
625 // everything
Winson Chung86f77532010-08-24 11:08:22 -0700626 final View currentPage = getPageAt(mCurrentPage);
627 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -0700628 }
629 }
630 }
631
632 @Override
633 public boolean onTouchEvent(MotionEvent ev) {
634 if (mVelocityTracker == null) {
635 mVelocityTracker = VelocityTracker.obtain();
636 }
637 mVelocityTracker.addMovement(ev);
638
639 final int action = ev.getAction();
640
641 switch (action & MotionEvent.ACTION_MASK) {
642 case MotionEvent.ACTION_DOWN:
643 /*
644 * If being flinged and user touches, stop the fling. isFinished
645 * will be false if being flinged.
646 */
647 if (!mScroller.isFinished()) {
648 mScroller.abortAnimation();
649 }
650
651 // Remember where the motion event started
652 mDownMotionX = mLastMotionX = ev.getX();
653 mActivePointerId = ev.getPointerId(0);
Michael Jurka0142d492010-08-25 17:46:15 -0700654 if (mTouchState == TOUCH_STATE_SCROLLING) {
655 pageBeginMoving();
656 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700657 break;
658
659 case MotionEvent.ACTION_MOVE:
660 if (mTouchState == TOUCH_STATE_SCROLLING) {
661 // Scroll to follow the motion event
662 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
663 final float x = ev.getX(pointerIndex);
664 final int deltaX = (int) (mLastMotionX - x);
665 mLastMotionX = x;
666
667 int sx = getScrollX();
668 if (deltaX < 0) {
669 if (sx > 0) {
Michael Jurka0142d492010-08-25 17:46:15 -0700670 mTouchX += Math.max(-mTouchX, deltaX);
671 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
672 if (!mDeferScrollUpdate) {
673 scrollBy(Math.max(-sx, deltaX), 0);
674 } else {
675 // This will trigger a call to computeScroll() on next drawChild() call
676 invalidate();
677 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700678 }
679 } else if (deltaX > 0) {
680 final int lastChildIndex = getChildCount() - 1;
681 final int availableToScroll = getChildOffset(lastChildIndex) -
682 getRelativeChildOffset(lastChildIndex) - sx;
683 if (availableToScroll > 0) {
Michael Jurka0142d492010-08-25 17:46:15 -0700684 mTouchX += Math.min(availableToScroll, deltaX);
685 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
686 if (!mDeferScrollUpdate) {
687 scrollBy(Math.min(availableToScroll, deltaX), 0);
688 } else {
689 // This will trigger a call to computeScroll() on next drawChild() call
690 invalidate();
691 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700692 }
693 } else {
694 awakenScrollBars();
695 }
696 } else if ((mTouchState == TOUCH_STATE_PREV_PAGE) ||
697 (mTouchState == TOUCH_STATE_NEXT_PAGE)) {
698 determineScrollingStart(ev);
699 }
700 break;
701
702 case MotionEvent.ACTION_UP:
703 if (mTouchState == TOUCH_STATE_SCROLLING) {
704 final int activePointerId = mActivePointerId;
705 final int pointerIndex = ev.findPointerIndex(activePointerId);
706 final float x = ev.getX(pointerIndex);
707 final VelocityTracker velocityTracker = mVelocityTracker;
708 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
709 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
710 boolean isfling = Math.abs(mDownMotionX - x) > MIN_LENGTH_FOR_FLING;
711
Michael Jurka0142d492010-08-25 17:46:15 -0700712 final int snapVelocity = mSnapVelocity;
713 if (isfling && velocityX > snapVelocity && mCurrentPage > 0) {
714 snapToPageWithVelocity(mCurrentPage - 1, velocityX);
715 } else if (isfling && velocityX < -snapVelocity &&
Winson Chung86f77532010-08-24 11:08:22 -0700716 mCurrentPage < getChildCount() - 1) {
Michael Jurka0142d492010-08-25 17:46:15 -0700717 snapToPageWithVelocity(mCurrentPage + 1, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -0700718 } else {
719 snapToDestination();
720 }
721
722 if (mVelocityTracker != null) {
723 mVelocityTracker.recycle();
724 mVelocityTracker = null;
725 }
726 } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
727 // at this point we have not moved beyond the touch slop
728 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
729 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -0700730 int nextPage = Math.max(0, mCurrentPage - 1);
731 if (nextPage != mCurrentPage) {
732 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700733 } else {
734 snapToDestination();
735 }
736 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
737 // at this point we have not moved beyond the touch slop
738 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
739 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -0700740 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
741 if (nextPage != mCurrentPage) {
742 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700743 } else {
744 snapToDestination();
745 }
746 }
747 mTouchState = TOUCH_STATE_REST;
748 mActivePointerId = INVALID_POINTER;
749 break;
750
751 case MotionEvent.ACTION_CANCEL:
752 mTouchState = TOUCH_STATE_REST;
753 mActivePointerId = INVALID_POINTER;
754 break;
755
756 case MotionEvent.ACTION_POINTER_UP:
757 onSecondaryPointerUp(ev);
758 break;
759 }
760
761 return true;
762 }
763
764 private void onSecondaryPointerUp(MotionEvent ev) {
765 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
766 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
767 final int pointerId = ev.getPointerId(pointerIndex);
768 if (pointerId == mActivePointerId) {
769 // This was our active pointer going up. Choose a new
770 // active pointer and adjust accordingly.
771 // TODO: Make this decision more intelligent.
772 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
773 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
774 mLastMotionY = ev.getY(newPointerIndex);
775 mActivePointerId = ev.getPointerId(newPointerIndex);
776 if (mVelocityTracker != null) {
777 mVelocityTracker.clear();
778 }
779 }
780 }
781
782 @Override
783 public void requestChildFocus(View child, View focused) {
784 super.requestChildFocus(child, focused);
Winson Chung86f77532010-08-24 11:08:22 -0700785 int page = indexOfChild(child);
786 if (page >= 0 && !isInTouchMode()) {
787 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -0700788 }
789 }
790
791 protected int getRelativeChildOffset(int index) {
792 return (getMeasuredWidth() - getChildAt(index).getMeasuredWidth()) / 2;
793 }
794
795 protected int getChildOffset(int index) {
796 if (getChildCount() == 0)
797 return 0;
798
799 int offset = getRelativeChildOffset(0);
800 for (int i = 0; i < index; ++i) {
801 offset += getChildAt(i).getMeasuredWidth();
802 }
803 return offset;
804 }
805
806 protected void snapToDestination() {
807 int minDistanceFromScreenCenter = getMeasuredWidth();
808 int minDistanceFromScreenCenterIndex = -1;
809 int screenCenter = mScrollX + (getMeasuredWidth() / 2);
810 final int childCount = getChildCount();
811 for (int i = 0; i < childCount; ++i) {
Michael Jurka0142d492010-08-25 17:46:15 -0700812 View layout = (View) getChildAt(i);
Winson Chung321e9ee2010-08-09 13:37:56 -0700813 int childWidth = layout.getMeasuredWidth();
814 int halfChildWidth = (childWidth / 2);
815 int childCenter = getChildOffset(i) + halfChildWidth;
816 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
817 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
818 minDistanceFromScreenCenter = distanceFromScreenCenter;
819 minDistanceFromScreenCenterIndex = i;
820 }
821 }
Winson Chung86f77532010-08-24 11:08:22 -0700822 snapToPage(minDistanceFromScreenCenterIndex, 1000);
Winson Chung321e9ee2010-08-09 13:37:56 -0700823 }
824
Michael Jurka0142d492010-08-25 17:46:15 -0700825 protected void snapToPageWithVelocity(int whichPage, int velocity) {
826 // We ignore velocity in this implementation, but children (e.g. SmoothPagedView)
827 // can use it
828 snapToPage(whichPage);
829 }
830
831 protected void snapToPage(int whichPage) {
Winson Chung86f77532010-08-24 11:08:22 -0700832 snapToPage(whichPage, 1000);
Winson Chung321e9ee2010-08-09 13:37:56 -0700833 }
834
Michael Jurka0142d492010-08-25 17:46:15 -0700835 protected void snapToPage(int whichPage, int duration) {
Winson Chung86f77532010-08-24 11:08:22 -0700836 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -0700837
Winson Chung321e9ee2010-08-09 13:37:56 -0700838
Winson Chung86f77532010-08-24 11:08:22 -0700839 int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700840 final int sX = getScrollX();
841 final int delta = newX - sX;
Michael Jurka0142d492010-08-25 17:46:15 -0700842 snapToPage(whichPage, delta, duration);
843 }
844
845 protected void snapToPage(int whichPage, int delta, int duration) {
846 mNextPage = whichPage;
847
848 View focusedChild = getFocusedChild();
849 if (focusedChild != null && whichPage != mCurrentPage &&
850 focusedChild == getChildAt(mCurrentPage)) {
851 focusedChild.clearFocus();
852 }
853
854 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -0700855 awakenScrollBars(duration);
856 if (duration == 0) {
857 duration = Math.abs(delta);
858 }
859
860 if (!mScroller.isFinished()) mScroller.abortAnimation();
Michael Jurka0142d492010-08-25 17:46:15 -0700861 mScroller.startScroll(getScrollX(), 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -0700862
863 // only load some associated pages
Winson Chung86f77532010-08-24 11:08:22 -0700864 loadAssociatedPages(mNextPage);
Michael Jurka0142d492010-08-25 17:46:15 -0700865 notifyPageSwitchListener();
Winson Chung321e9ee2010-08-09 13:37:56 -0700866 invalidate();
867 }
868
869 @Override
870 protected Parcelable onSaveInstanceState() {
871 final SavedState state = new SavedState(super.onSaveInstanceState());
Winson Chung86f77532010-08-24 11:08:22 -0700872 state.currentPage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700873 return state;
874 }
875
876 @Override
877 protected void onRestoreInstanceState(Parcelable state) {
878 SavedState savedState = (SavedState) state;
879 super.onRestoreInstanceState(savedState.getSuperState());
Winson Chung86f77532010-08-24 11:08:22 -0700880 if (savedState.currentPage != -1) {
881 mCurrentPage = savedState.currentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700882 }
883 }
884
885 public void scrollLeft() {
886 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -0700887 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -0700888 } else {
Winson Chung86f77532010-08-24 11:08:22 -0700889 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -0700890 }
891 }
892
893 public void scrollRight() {
894 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -0700895 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -0700896 } else {
Winson Chung86f77532010-08-24 11:08:22 -0700897 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -0700898 }
899 }
900
Winson Chung86f77532010-08-24 11:08:22 -0700901 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700902 int result = -1;
903 if (v != null) {
904 ViewParent vp = v.getParent();
905 int count = getChildCount();
906 for (int i = 0; i < count; i++) {
907 if (vp == getChildAt(i)) {
908 return i;
909 }
910 }
911 }
912 return result;
913 }
914
915 /**
916 * @return True is long presses are still allowed for the current touch
917 */
918 public boolean allowLongPress() {
919 return mAllowLongPress;
920 }
921
Michael Jurka0142d492010-08-25 17:46:15 -0700922 /**
923 * Set true to allow long-press events to be triggered, usually checked by
924 * {@link Launcher} to accept or block dpad-initiated long-presses.
925 */
926 public void setAllowLongPress(boolean allowLongPress) {
927 mAllowLongPress = allowLongPress;
928 }
929
Winson Chung321e9ee2010-08-09 13:37:56 -0700930 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -0700931 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700932
933 SavedState(Parcelable superState) {
934 super(superState);
935 }
936
937 private SavedState(Parcel in) {
938 super(in);
Winson Chung86f77532010-08-24 11:08:22 -0700939 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -0700940 }
941
942 @Override
943 public void writeToParcel(Parcel out, int flags) {
944 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -0700945 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700946 }
947
948 public static final Parcelable.Creator<SavedState> CREATOR =
949 new Parcelable.Creator<SavedState>() {
950 public SavedState createFromParcel(Parcel in) {
951 return new SavedState(in);
952 }
953
954 public SavedState[] newArray(int size) {
955 return new SavedState[size];
956 }
957 };
958 }
959
Winson Chung86f77532010-08-24 11:08:22 -0700960 public void loadAssociatedPages(int page) {
Michael Jurka0142d492010-08-25 17:46:15 -0700961 if (mContentIsRefreshable) {
962 final int count = getChildCount();
963 if (page < count) {
964 int lowerPageBound = Math.max(0, page - 1);
965 int upperPageBound = Math.min(page + 1, count - 1);
966 for (int i = 0; i < count; ++i) {
967 final ViewGroup layout = (ViewGroup) getChildAt(i);
968 final int childCount = layout.getChildCount();
969 if (lowerPageBound <= i && i <= upperPageBound) {
970 if (mDirtyPageContent.get(i)) {
971 syncPageItems(i);
972 mDirtyPageContent.set(i, false);
973 }
974 } else {
975 if (childCount > 0) {
976 layout.removeAllViews();
977 }
978 mDirtyPageContent.set(i, true);
Winson Chung86f77532010-08-24 11:08:22 -0700979 }
Winson Chung80baf5a2010-08-09 16:03:15 -0700980 }
981 }
Winson Chung80baf5a2010-08-09 16:03:15 -0700982 }
983 }
984
Winson Chung86f77532010-08-24 11:08:22 -0700985 /**
986 * This method is called ONLY to synchronize the number of pages that the paged view has.
987 * To actually fill the pages with information, implement syncPageItems() below. It is
988 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
989 * and therefore, individual page items do not need to be updated in this method.
990 */
Winson Chung321e9ee2010-08-09 13:37:56 -0700991 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -0700992
993 /**
994 * This method is called to synchronize the items that are on a particular page. If views on
995 * the page can be reused, then they should be updated within this method.
996 */
Winson Chung321e9ee2010-08-09 13:37:56 -0700997 public abstract void syncPageItems(int page);
Winson Chung86f77532010-08-24 11:08:22 -0700998
Winson Chung321e9ee2010-08-09 13:37:56 -0700999 public void invalidatePageData() {
Michael Jurka0142d492010-08-25 17:46:15 -07001000 if (mContentIsRefreshable) {
1001 // Update all the pages
1002 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07001003
Michael Jurka0142d492010-08-25 17:46:15 -07001004 // Mark each of the pages as dirty
1005 final int count = getChildCount();
1006 mDirtyPageContent.clear();
1007 for (int i = 0; i < count; ++i) {
1008 mDirtyPageContent.add(true);
1009 }
1010
1011 // Load any pages that are necessary for the current window of views
1012 loadAssociatedPages(mCurrentPage);
1013 mDirtyPageAlpha = true;
1014 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07001015 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001016 }
1017}