OSDN Git Service

dd312a664c96abfcfa13113db03a2c94f9c69728
[android-x86/frameworks-base.git] / core / java / android / widget / ScrollView.java
1 /*
2  * Copyright (C) 2006 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
17 package android.widget;
18
19 import android.os.Build;
20 import android.os.Parcel;
21 import android.os.Parcelable;
22 import com.android.internal.R;
23
24 import android.content.Context;
25 import android.content.res.TypedArray;
26 import android.graphics.Canvas;
27 import android.graphics.Rect;
28 import android.os.Bundle;
29 import android.os.StrictMode;
30 import android.util.AttributeSet;
31 import android.util.Log;
32 import android.view.FocusFinder;
33 import android.view.InputDevice;
34 import android.view.KeyEvent;
35 import android.view.MotionEvent;
36 import android.view.VelocityTracker;
37 import android.view.View;
38 import android.view.ViewConfiguration;
39 import android.view.ViewDebug;
40 import android.view.ViewGroup;
41 import android.view.ViewParent;
42 import android.view.accessibility.AccessibilityEvent;
43 import android.view.accessibility.AccessibilityNodeInfo;
44 import android.view.animation.AnimationUtils;
45
46 import java.util.List;
47
48 /**
49  * Layout container for a view hierarchy that can be scrolled by the user,
50  * allowing it to be larger than the physical display.  A ScrollView
51  * is a {@link FrameLayout}, meaning you should place one child in it
52  * containing the entire contents to scroll; this child may itself be a layout
53  * manager with a complex hierarchy of objects.  A child that is often used
54  * is a {@link LinearLayout} in a vertical orientation, presenting a vertical
55  * array of top-level items that the user can scroll through.
56  * <p>You should never use a ScrollView with a {@link ListView}, because
57  * ListView takes care of its own vertical scrolling.  Most importantly, doing this
58  * defeats all of the important optimizations in ListView for dealing with
59  * large lists, since it effectively forces the ListView to display its entire
60  * list of items to fill up the infinite container supplied by ScrollView.
61  * <p>The {@link TextView} class also
62  * takes care of its own scrolling, so does not require a ScrollView, but
63  * using the two together is possible to achieve the effect of a text view
64  * within a larger container.
65  *
66  * <p>ScrollView only supports vertical scrolling. For horizontal scrolling,
67  * use {@link HorizontalScrollView}.
68  *
69  * @attr ref android.R.styleable#ScrollView_fillViewport
70  */
71 public class ScrollView extends FrameLayout {
72     static final int ANIMATED_SCROLL_GAP = 250;
73
74     static final float MAX_SCROLL_FACTOR = 0.5f;
75
76     private static final String TAG = "ScrollView";
77
78     private long mLastScroll;
79
80     private final Rect mTempRect = new Rect();
81     private OverScroller mScroller;
82     private EdgeEffect mEdgeGlowTop;
83     private EdgeEffect mEdgeGlowBottom;
84
85     /**
86      * Position of the last motion event.
87      */
88     private int mLastMotionY;
89
90     /**
91      * True when the layout has changed but the traversal has not come through yet.
92      * Ideally the view hierarchy would keep track of this for us.
93      */
94     private boolean mIsLayoutDirty = true;
95
96     /**
97      * The child to give focus to in the event that a child has requested focus while the
98      * layout is dirty. This prevents the scroll from being wrong if the child has not been
99      * laid out before requesting focus.
100      */
101     private View mChildToScrollTo = null;
102
103     /**
104      * True if the user is currently dragging this ScrollView around. This is
105      * not the same as 'is being flinged', which can be checked by
106      * mScroller.isFinished() (flinging begins when the user lifts his finger).
107      */
108     private boolean mIsBeingDragged = false;
109
110     /**
111      * Determines speed during touch scrolling
112      */
113     private VelocityTracker mVelocityTracker;
114
115     /**
116      * When set to true, the scroll view measure its child to make it fill the currently
117      * visible area.
118      */
119     @ViewDebug.ExportedProperty(category = "layout")
120     private boolean mFillViewport;
121
122     /**
123      * Whether arrow scrolling is animated.
124      */
125     private boolean mSmoothScrollingEnabled = true;
126
127     private int mTouchSlop;
128     private int mMinimumVelocity;
129     private int mMaximumVelocity;
130
131     private int mOverscrollDistance;
132     private int mOverflingDistance;
133
134     /**
135      * ID of the active pointer. This is used to retain consistency during
136      * drags/flings if multiple pointers are used.
137      */
138     private int mActivePointerId = INVALID_POINTER;
139
140     /**
141      * Used during scrolling to retrieve the new offset within the window.
142      */
143     private final int[] mScrollOffset = new int[2];
144     private final int[] mScrollConsumed = new int[2];
145
146     /**
147      * The StrictMode "critical time span" objects to catch animation
148      * stutters.  Non-null when a time-sensitive animation is
149      * in-flight.  Must call finish() on them when done animating.
150      * These are no-ops on user builds.
151      */
152     private StrictMode.Span mScrollStrictSpan = null;  // aka "drag"
153     private StrictMode.Span mFlingStrictSpan = null;
154
155     /**
156      * Sentinel value for no current active pointer.
157      * Used by {@link #mActivePointerId}.
158      */
159     private static final int INVALID_POINTER = -1;
160
161     private SavedState mSavedState;
162
163     public ScrollView(Context context) {
164         this(context, null);
165     }
166
167     public ScrollView(Context context, AttributeSet attrs) {
168         this(context, attrs, com.android.internal.R.attr.scrollViewStyle);
169     }
170
171     public ScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
172         this(context, attrs, defStyleAttr, 0);
173     }
174
175     public ScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
176         super(context, attrs, defStyleAttr, defStyleRes);
177         initScrollView();
178
179         final TypedArray a = context.obtainStyledAttributes(
180                 attrs, com.android.internal.R.styleable.ScrollView, defStyleAttr, defStyleRes);
181
182         setFillViewport(a.getBoolean(R.styleable.ScrollView_fillViewport, false));
183
184         a.recycle();
185     }
186
187     @Override
188     public boolean shouldDelayChildPressedState() {
189         return true;
190     }
191
192     @Override
193     protected float getTopFadingEdgeStrength() {
194         if (getChildCount() == 0) {
195             return 0.0f;
196         }
197
198         final int length = getVerticalFadingEdgeLength();
199         if (mScrollY < length) {
200             return mScrollY / (float) length;
201         }
202
203         return 1.0f;
204     }
205
206     @Override
207     protected float getBottomFadingEdgeStrength() {
208         if (getChildCount() == 0) {
209             return 0.0f;
210         }
211
212         final int length = getVerticalFadingEdgeLength();
213         final int bottomEdge = getHeight() - mPaddingBottom;
214         final int span = getChildAt(0).getBottom() - mScrollY - bottomEdge;
215         if (span < length) {
216             return span / (float) length;
217         }
218
219         return 1.0f;
220     }
221
222     /**
223      * @return The maximum amount this scroll view will scroll in response to
224      *   an arrow event.
225      */
226     public int getMaxScrollAmount() {
227         return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop));
228     }
229
230
231     private void initScrollView() {
232         mScroller = new OverScroller(getContext());
233         setFocusable(true);
234         setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
235         setWillNotDraw(false);
236         final ViewConfiguration configuration = ViewConfiguration.get(mContext);
237         mTouchSlop = configuration.getScaledTouchSlop();
238         mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
239         mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
240         mOverscrollDistance = configuration.getScaledOverscrollDistance();
241         mOverflingDistance = configuration.getScaledOverflingDistance();
242     }
243
244     @Override
245     public void addView(View child) {
246         if (getChildCount() > 0) {
247             throw new IllegalStateException("ScrollView can host only one direct child");
248         }
249
250         super.addView(child);
251     }
252
253     @Override
254     public void addView(View child, int index) {
255         if (getChildCount() > 0) {
256             throw new IllegalStateException("ScrollView can host only one direct child");
257         }
258
259         super.addView(child, index);
260     }
261
262     @Override
263     public void addView(View child, ViewGroup.LayoutParams params) {
264         if (getChildCount() > 0) {
265             throw new IllegalStateException("ScrollView can host only one direct child");
266         }
267
268         super.addView(child, params);
269     }
270
271     @Override
272     public void addView(View child, int index, ViewGroup.LayoutParams params) {
273         if (getChildCount() > 0) {
274             throw new IllegalStateException("ScrollView can host only one direct child");
275         }
276
277         super.addView(child, index, params);
278     }
279
280     /**
281      * @return Returns true this ScrollView can be scrolled
282      */
283     private boolean canScroll() {
284         View child = getChildAt(0);
285         if (child != null) {
286             int childHeight = child.getHeight();
287             return getHeight() < childHeight + mPaddingTop + mPaddingBottom;
288         }
289         return false;
290     }
291
292     /**
293      * Indicates whether this ScrollView's content is stretched to fill the viewport.
294      *
295      * @return True if the content fills the viewport, false otherwise.
296      *
297      * @attr ref android.R.styleable#ScrollView_fillViewport
298      */
299     public boolean isFillViewport() {
300         return mFillViewport;
301     }
302
303     /**
304      * Indicates this ScrollView whether it should stretch its content height to fill
305      * the viewport or not.
306      *
307      * @param fillViewport True to stretch the content's height to the viewport's
308      *        boundaries, false otherwise.
309      *
310      * @attr ref android.R.styleable#ScrollView_fillViewport
311      */
312     public void setFillViewport(boolean fillViewport) {
313         if (fillViewport != mFillViewport) {
314             mFillViewport = fillViewport;
315             requestLayout();
316         }
317     }
318
319     /**
320      * @return Whether arrow scrolling will animate its transition.
321      */
322     public boolean isSmoothScrollingEnabled() {
323         return mSmoothScrollingEnabled;
324     }
325
326     /**
327      * Set whether arrow scrolling will animate its transition.
328      * @param smoothScrollingEnabled whether arrow scrolling will animate its transition
329      */
330     public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) {
331         mSmoothScrollingEnabled = smoothScrollingEnabled;
332     }
333
334     @Override
335     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
336         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
337
338         if (!mFillViewport) {
339             return;
340         }
341
342         final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
343         if (heightMode == MeasureSpec.UNSPECIFIED) {
344             return;
345         }
346
347         if (getChildCount() > 0) {
348             final View child = getChildAt(0);
349             int height = getMeasuredHeight();
350             if (child.getMeasuredHeight() < height) {
351                 final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams();
352
353                 int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
354                         mPaddingLeft + mPaddingRight, lp.width);
355                 height -= mPaddingTop;
356                 height -= mPaddingBottom;
357                 int childHeightMeasureSpec =
358                         MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
359
360                 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
361             }
362         }
363     }
364
365     @Override
366     public boolean dispatchKeyEvent(KeyEvent event) {
367         // Let the focused view and/or our descendants get the key first
368         return super.dispatchKeyEvent(event) || executeKeyEvent(event);
369     }
370
371     /**
372      * You can call this function yourself to have the scroll view perform
373      * scrolling from a key event, just as if the event had been dispatched to
374      * it by the view hierarchy.
375      *
376      * @param event The key event to execute.
377      * @return Return true if the event was handled, else false.
378      */
379     public boolean executeKeyEvent(KeyEvent event) {
380         mTempRect.setEmpty();
381
382         if (!canScroll()) {
383             if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
384                 View currentFocused = findFocus();
385                 if (currentFocused == this) currentFocused = null;
386                 View nextFocused = FocusFinder.getInstance().findNextFocus(this,
387                         currentFocused, View.FOCUS_DOWN);
388                 return nextFocused != null
389                         && nextFocused != this
390                         && nextFocused.requestFocus(View.FOCUS_DOWN);
391             }
392             return false;
393         }
394
395         boolean handled = false;
396         if (event.getAction() == KeyEvent.ACTION_DOWN) {
397             switch (event.getKeyCode()) {
398                 case KeyEvent.KEYCODE_DPAD_UP:
399                     if (!event.isAltPressed()) {
400                         handled = arrowScroll(View.FOCUS_UP);
401                     } else {
402                         handled = fullScroll(View.FOCUS_UP);
403                     }
404                     break;
405                 case KeyEvent.KEYCODE_DPAD_DOWN:
406                     if (!event.isAltPressed()) {
407                         handled = arrowScroll(View.FOCUS_DOWN);
408                     } else {
409                         handled = fullScroll(View.FOCUS_DOWN);
410                     }
411                     break;
412                 case KeyEvent.KEYCODE_SPACE:
413                     pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN);
414                     break;
415             }
416         }
417
418         return handled;
419     }
420
421     private boolean inChild(int x, int y) {
422         if (getChildCount() > 0) {
423             final int scrollY = mScrollY;
424             final View child = getChildAt(0);
425             return !(y < child.getTop() - scrollY
426                     || y >= child.getBottom() - scrollY
427                     || x < child.getLeft()
428                     || x >= child.getRight());
429         }
430         return false;
431     }
432
433     private void initOrResetVelocityTracker() {
434         if (mVelocityTracker == null) {
435             mVelocityTracker = VelocityTracker.obtain();
436         } else {
437             mVelocityTracker.clear();
438         }
439     }
440
441     private void initVelocityTrackerIfNotExists() {
442         if (mVelocityTracker == null) {
443             mVelocityTracker = VelocityTracker.obtain();
444         }
445     }
446
447     private void recycleVelocityTracker() {
448         if (mVelocityTracker != null) {
449             mVelocityTracker.recycle();
450             mVelocityTracker = null;
451         }
452     }
453
454     @Override
455     public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
456         if (disallowIntercept) {
457             recycleVelocityTracker();
458         }
459         super.requestDisallowInterceptTouchEvent(disallowIntercept);
460     }
461
462
463     @Override
464     public boolean onInterceptTouchEvent(MotionEvent ev) {
465         /*
466          * This method JUST determines whether we want to intercept the motion.
467          * If we return true, onMotionEvent will be called and we do the actual
468          * scrolling there.
469          */
470
471         /*
472         * Shortcut the most recurring case: the user is in the dragging
473         * state and he is moving his finger.  We want to intercept this
474         * motion.
475         */
476         final int action = ev.getAction();
477         if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
478             return true;
479         }
480
481         /*
482          * Don't try to intercept touch if we can't scroll anyway.
483          */
484         if (getScrollY() == 0 && !canScrollVertically(1)) {
485             return false;
486         }
487
488         switch (action & MotionEvent.ACTION_MASK) {
489             case MotionEvent.ACTION_MOVE: {
490                 /*
491                  * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
492                  * whether the user has moved far enough from his original down touch.
493                  */
494
495                 /*
496                 * Locally do absolute value. mLastMotionY is set to the y value
497                 * of the down event.
498                 */
499                 final int activePointerId = mActivePointerId;
500                 if (activePointerId == INVALID_POINTER) {
501                     // If we don't have a valid id, the touch down wasn't on content.
502                     break;
503                 }
504
505                 final int pointerIndex = ev.findPointerIndex(activePointerId);
506                 if (pointerIndex == -1) {
507                     Log.e(TAG, "Invalid pointerId=" + activePointerId
508                             + " in onInterceptTouchEvent");
509                     break;
510                 }
511
512                 final int y = (int) ev.getY(pointerIndex);
513                 final int yDiff = Math.abs(y - mLastMotionY);
514                 if (yDiff > mTouchSlop && (getNestedScrollAxes() & SCROLL_AXIS_VERTICAL) == 0) {
515                     mIsBeingDragged = true;
516                     mLastMotionY = y;
517                     initVelocityTrackerIfNotExists();
518                     mVelocityTracker.addMovement(ev);
519                     if (mScrollStrictSpan == null) {
520                         mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll");
521                     }
522                     final ViewParent parent = getParent();
523                     if (parent != null) {
524                         parent.requestDisallowInterceptTouchEvent(true);
525                     }
526                 }
527                 break;
528             }
529
530             case MotionEvent.ACTION_DOWN: {
531                 final int y = (int) ev.getY();
532                 if (!inChild((int) ev.getX(), (int) y)) {
533                     mIsBeingDragged = false;
534                     recycleVelocityTracker();
535                     break;
536                 }
537
538                 /*
539                  * Remember location of down touch.
540                  * ACTION_DOWN always refers to pointer index 0.
541                  */
542                 mLastMotionY = y;
543                 mActivePointerId = ev.getPointerId(0);
544
545                 initOrResetVelocityTracker();
546                 mVelocityTracker.addMovement(ev);
547                 /*
548                 * If being flinged and user touches the screen, initiate drag;
549                 * otherwise don't.  mScroller.isFinished should be false when
550                 * being flinged.
551                 */
552                 mIsBeingDragged = !mScroller.isFinished();
553                 if (mIsBeingDragged && mScrollStrictSpan == null) {
554                     mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll");
555                 }
556                 startNestedScroll(SCROLL_AXIS_VERTICAL);
557                 break;
558             }
559
560             case MotionEvent.ACTION_CANCEL:
561             case MotionEvent.ACTION_UP:
562                 /* Release the drag */
563                 mIsBeingDragged = false;
564                 mActivePointerId = INVALID_POINTER;
565                 recycleVelocityTracker();
566                 if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) {
567                     postInvalidateOnAnimation();
568                 }
569                 stopNestedScroll();
570                 break;
571             case MotionEvent.ACTION_POINTER_UP:
572                 onSecondaryPointerUp(ev);
573                 break;
574         }
575
576         /*
577         * The only time we want to intercept motion events is if we are in the
578         * drag mode.
579         */
580         return mIsBeingDragged;
581     }
582
583     @Override
584     public boolean onTouchEvent(MotionEvent ev) {
585         initVelocityTrackerIfNotExists();
586
587         MotionEvent vtev = MotionEvent.obtain(ev);
588
589         final int action = ev.getAction();
590
591         switch (action & MotionEvent.ACTION_MASK) {
592             case MotionEvent.ACTION_DOWN: {
593                 if (getChildCount() == 0) {
594                     return false;
595                 }
596                 if ((mIsBeingDragged = !mScroller.isFinished())) {
597                     final ViewParent parent = getParent();
598                     if (parent != null) {
599                         parent.requestDisallowInterceptTouchEvent(true);
600                     }
601                 }
602
603                 /*
604                  * If being flinged and user touches, stop the fling. isFinished
605                  * will be false if being flinged.
606                  */
607                 if (!mScroller.isFinished()) {
608                     mScroller.abortAnimation();
609                     if (mFlingStrictSpan != null) {
610                         mFlingStrictSpan.finish();
611                         mFlingStrictSpan = null;
612                     }
613                 }
614
615                 // Remember where the motion event started
616                 mLastMotionY = (int) ev.getY();
617                 mActivePointerId = ev.getPointerId(0);
618                 startNestedScroll(SCROLL_AXIS_VERTICAL);
619                 break;
620             }
621             case MotionEvent.ACTION_MOVE:
622                 final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
623                 if (activePointerIndex == -1) {
624                     Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
625                     break;
626                 }
627
628                 final int y = (int) ev.getY(activePointerIndex);
629                 int deltaY = mLastMotionY - y;
630                 if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) {
631                     deltaY -= mScrollConsumed[1];
632                     vtev.offsetLocation(0, mScrollOffset[1]);
633                 }
634                 if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) {
635                     final ViewParent parent = getParent();
636                     if (parent != null) {
637                         parent.requestDisallowInterceptTouchEvent(true);
638                     }
639                     mIsBeingDragged = true;
640                     if (deltaY > 0) {
641                         deltaY -= mTouchSlop;
642                     } else {
643                         deltaY += mTouchSlop;
644                     }
645                 }
646                 if (mIsBeingDragged) {
647                     // Scroll to follow the motion event
648                     mLastMotionY = y - mScrollOffset[1];
649
650                     final int oldY = mScrollY;
651                     final int range = getScrollRange();
652                     final int overscrollMode = getOverScrollMode();
653                     boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS ||
654                             (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0);
655
656                     // Calling overScrollBy will call onOverScrolled, which
657                     // calls onScrollChanged if applicable.
658                     if (overScrollBy(0, deltaY, 0, mScrollY, 0, range, 0, mOverscrollDistance, true)
659                             && !hasNestedScrollingParent()) {
660                         // Break our velocity if we hit a scroll barrier.
661                         mVelocityTracker.clear();
662                     }
663
664                     final int scrolledDeltaY = mScrollY - oldY;
665                     final int unconsumedY = deltaY - scrolledDeltaY;
666                     if (dispatchNestedScroll(0, scrolledDeltaY, 0, unconsumedY, mScrollOffset)) {
667                         mLastMotionY -= mScrollOffset[1];
668                         vtev.offsetLocation(0, mScrollOffset[1]);
669                     } else if (canOverscroll) {
670                         final int pulledToY = oldY + deltaY;
671                         if (pulledToY < 0) {
672                             mEdgeGlowTop.onPull((float) deltaY / getHeight(),
673                                     ev.getX(activePointerIndex) / getWidth());
674                             if (!mEdgeGlowBottom.isFinished()) {
675                                 mEdgeGlowBottom.onRelease();
676                             }
677                         } else if (pulledToY > range) {
678                             mEdgeGlowBottom.onPull((float) deltaY / getHeight(),
679                                     1.f - ev.getX(activePointerIndex) / getWidth());
680                             if (!mEdgeGlowTop.isFinished()) {
681                                 mEdgeGlowTop.onRelease();
682                             }
683                         }
684                         if (mEdgeGlowTop != null
685                                 && (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) {
686                             postInvalidateOnAnimation();
687                         }
688                     }
689                 }
690                 break;
691             case MotionEvent.ACTION_UP:
692                 if (mIsBeingDragged) {
693                     final VelocityTracker velocityTracker = mVelocityTracker;
694                     velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
695                     int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
696
697                     if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
698                         flingWithNestedDispatch(-initialVelocity);
699                     } else if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0,
700                             getScrollRange())) {
701                         postInvalidateOnAnimation();
702                     }
703
704                     mActivePointerId = INVALID_POINTER;
705                     endDrag();
706                 }
707                 break;
708             case MotionEvent.ACTION_CANCEL:
709                 if (mIsBeingDragged && getChildCount() > 0) {
710                     if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) {
711                         postInvalidateOnAnimation();
712                     }
713                     mActivePointerId = INVALID_POINTER;
714                     endDrag();
715                 }
716                 break;
717             case MotionEvent.ACTION_POINTER_DOWN: {
718                 final int index = ev.getActionIndex();
719                 mLastMotionY = (int) ev.getY(index);
720                 mActivePointerId = ev.getPointerId(index);
721                 break;
722             }
723             case MotionEvent.ACTION_POINTER_UP:
724                 onSecondaryPointerUp(ev);
725                 mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId));
726                 break;
727         }
728
729         if (mVelocityTracker != null) {
730             mVelocityTracker.addMovement(vtev);
731         }
732         vtev.recycle();
733         return true;
734     }
735
736     private void onSecondaryPointerUp(MotionEvent ev) {
737         final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
738                 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
739         final int pointerId = ev.getPointerId(pointerIndex);
740         if (pointerId == mActivePointerId) {
741             // This was our active pointer going up. Choose a new
742             // active pointer and adjust accordingly.
743             // TODO: Make this decision more intelligent.
744             final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
745             mLastMotionY = (int) ev.getY(newPointerIndex);
746             mActivePointerId = ev.getPointerId(newPointerIndex);
747             if (mVelocityTracker != null) {
748                 mVelocityTracker.clear();
749             }
750         }
751     }
752
753     @Override
754     public boolean onGenericMotionEvent(MotionEvent event) {
755         if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
756             switch (event.getAction()) {
757                 case MotionEvent.ACTION_SCROLL: {
758                     if (!mIsBeingDragged) {
759                         final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
760                         if (vscroll != 0) {
761                             final int delta = (int) (vscroll * getVerticalScrollFactor());
762                             final int range = getScrollRange();
763                             int oldScrollY = mScrollY;
764                             int newScrollY = oldScrollY - delta;
765                             if (newScrollY < 0) {
766                                 newScrollY = 0;
767                             } else if (newScrollY > range) {
768                                 newScrollY = range;
769                             }
770                             if (newScrollY != oldScrollY) {
771                                 super.scrollTo(mScrollX, newScrollY);
772                                 return true;
773                             }
774                         }
775                     }
776                 }
777             }
778         }
779         return super.onGenericMotionEvent(event);
780     }
781
782     @Override
783     protected void onOverScrolled(int scrollX, int scrollY,
784             boolean clampedX, boolean clampedY) {
785         // Treat animating scrolls differently; see #computeScroll() for why.
786         if (!mScroller.isFinished()) {
787             final int oldX = mScrollX;
788             final int oldY = mScrollY;
789             mScrollX = scrollX;
790             mScrollY = scrollY;
791             invalidateParentIfNeeded();
792             onScrollChanged(mScrollX, mScrollY, oldX, oldY);
793             if (clampedY) {
794                 mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange());
795             }
796         } else {
797             super.scrollTo(scrollX, scrollY);
798         }
799
800         awakenScrollBars();
801     }
802
803     @Override
804     public boolean performAccessibilityAction(int action, Bundle arguments) {
805         if (super.performAccessibilityAction(action, arguments)) {
806             return true;
807         }
808         if (!isEnabled()) {
809             return false;
810         }
811         switch (action) {
812             case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
813                 final int viewportHeight = getHeight() - mPaddingBottom - mPaddingTop;
814                 final int targetScrollY = Math.min(mScrollY + viewportHeight, getScrollRange());
815                 if (targetScrollY != mScrollY) {
816                     smoothScrollTo(0, targetScrollY);
817                     return true;
818                 }
819             } return false;
820             case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
821                 final int viewportHeight = getHeight() - mPaddingBottom - mPaddingTop;
822                 final int targetScrollY = Math.max(mScrollY - viewportHeight, 0);
823                 if (targetScrollY != mScrollY) {
824                     smoothScrollTo(0, targetScrollY);
825                     return true;
826                 }
827             } return false;
828         }
829         return false;
830     }
831
832     @Override
833     public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
834         super.onInitializeAccessibilityNodeInfo(info);
835         info.setClassName(ScrollView.class.getName());
836         if (isEnabled()) {
837             final int scrollRange = getScrollRange();
838             if (scrollRange > 0) {
839                 info.setScrollable(true);
840                 if (mScrollY > 0) {
841                     info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
842                 }
843                 if (mScrollY < scrollRange) {
844                     info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
845                 }
846             }
847         }
848     }
849
850     @Override
851     public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
852         super.onInitializeAccessibilityEvent(event);
853         event.setClassName(ScrollView.class.getName());
854         final boolean scrollable = getScrollRange() > 0;
855         event.setScrollable(scrollable);
856         event.setScrollX(mScrollX);
857         event.setScrollY(mScrollY);
858         event.setMaxScrollX(mScrollX);
859         event.setMaxScrollY(getScrollRange());
860     }
861
862     private int getScrollRange() {
863         int scrollRange = 0;
864         if (getChildCount() > 0) {
865             View child = getChildAt(0);
866             scrollRange = Math.max(0,
867                     child.getHeight() - (getHeight() - mPaddingBottom - mPaddingTop));
868         }
869         return scrollRange;
870     }
871
872     /**
873      * <p>
874      * Finds the next focusable component that fits in the specified bounds.
875      * </p>
876      *
877      * @param topFocus look for a candidate is the one at the top of the bounds
878      *                 if topFocus is true, or at the bottom of the bounds if topFocus is
879      *                 false
880      * @param top      the top offset of the bounds in which a focusable must be
881      *                 found
882      * @param bottom   the bottom offset of the bounds in which a focusable must
883      *                 be found
884      * @return the next focusable component in the bounds or null if none can
885      *         be found
886      */
887     private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) {
888
889         List<View> focusables = getFocusables(View.FOCUS_FORWARD);
890         View focusCandidate = null;
891
892         /*
893          * A fully contained focusable is one where its top is below the bound's
894          * top, and its bottom is above the bound's bottom. A partially
895          * contained focusable is one where some part of it is within the
896          * bounds, but it also has some part that is not within bounds.  A fully contained
897          * focusable is preferred to a partially contained focusable.
898          */
899         boolean foundFullyContainedFocusable = false;
900
901         int count = focusables.size();
902         for (int i = 0; i < count; i++) {
903             View view = focusables.get(i);
904             int viewTop = view.getTop();
905             int viewBottom = view.getBottom();
906
907             if (top < viewBottom && viewTop < bottom) {
908                 /*
909                  * the focusable is in the target area, it is a candidate for
910                  * focusing
911                  */
912
913                 final boolean viewIsFullyContained = (top < viewTop) &&
914                         (viewBottom < bottom);
915
916                 if (focusCandidate == null) {
917                     /* No candidate, take this one */
918                     focusCandidate = view;
919                     foundFullyContainedFocusable = viewIsFullyContained;
920                 } else {
921                     final boolean viewIsCloserToBoundary =
922                             (topFocus && viewTop < focusCandidate.getTop()) ||
923                                     (!topFocus && viewBottom > focusCandidate
924                                             .getBottom());
925
926                     if (foundFullyContainedFocusable) {
927                         if (viewIsFullyContained && viewIsCloserToBoundary) {
928                             /*
929                              * We're dealing with only fully contained views, so
930                              * it has to be closer to the boundary to beat our
931                              * candidate
932                              */
933                             focusCandidate = view;
934                         }
935                     } else {
936                         if (viewIsFullyContained) {
937                             /* Any fully contained view beats a partially contained view */
938                             focusCandidate = view;
939                             foundFullyContainedFocusable = true;
940                         } else if (viewIsCloserToBoundary) {
941                             /*
942                              * Partially contained view beats another partially
943                              * contained view if it's closer
944                              */
945                             focusCandidate = view;
946                         }
947                     }
948                 }
949             }
950         }
951
952         return focusCandidate;
953     }
954
955     /**
956      * <p>Handles scrolling in response to a "page up/down" shortcut press. This
957      * method will scroll the view by one page up or down and give the focus
958      * to the topmost/bottommost component in the new visible area. If no
959      * component is a good candidate for focus, this scrollview reclaims the
960      * focus.</p>
961      *
962      * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
963      *                  to go one page up or
964      *                  {@link android.view.View#FOCUS_DOWN} to go one page down
965      * @return true if the key event is consumed by this method, false otherwise
966      */
967     public boolean pageScroll(int direction) {
968         boolean down = direction == View.FOCUS_DOWN;
969         int height = getHeight();
970
971         if (down) {
972             mTempRect.top = getScrollY() + height;
973             int count = getChildCount();
974             if (count > 0) {
975                 View view = getChildAt(count - 1);
976                 if (mTempRect.top + height > view.getBottom()) {
977                     mTempRect.top = view.getBottom() - height;
978                 }
979             }
980         } else {
981             mTempRect.top = getScrollY() - height;
982             if (mTempRect.top < 0) {
983                 mTempRect.top = 0;
984             }
985         }
986         mTempRect.bottom = mTempRect.top + height;
987
988         return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
989     }
990
991     /**
992      * <p>Handles scrolling in response to a "home/end" shortcut press. This
993      * method will scroll the view to the top or bottom and give the focus
994      * to the topmost/bottommost component in the new visible area. If no
995      * component is a good candidate for focus, this scrollview reclaims the
996      * focus.</p>
997      *
998      * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
999      *                  to go the top of the view or
1000      *                  {@link android.view.View#FOCUS_DOWN} to go the bottom
1001      * @return true if the key event is consumed by this method, false otherwise
1002      */
1003     public boolean fullScroll(int direction) {
1004         boolean down = direction == View.FOCUS_DOWN;
1005         int height = getHeight();
1006
1007         mTempRect.top = 0;
1008         mTempRect.bottom = height;
1009
1010         if (down) {
1011             int count = getChildCount();
1012             if (count > 0) {
1013                 View view = getChildAt(count - 1);
1014                 mTempRect.bottom = view.getBottom() + mPaddingBottom;
1015                 mTempRect.top = mTempRect.bottom - height;
1016             }
1017         }
1018
1019         return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
1020     }
1021
1022     /**
1023      * <p>Scrolls the view to make the area defined by <code>top</code> and
1024      * <code>bottom</code> visible. This method attempts to give the focus
1025      * to a component visible in this area. If no component can be focused in
1026      * the new visible area, the focus is reclaimed by this ScrollView.</p>
1027      *
1028      * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
1029      *                  to go upward, {@link android.view.View#FOCUS_DOWN} to downward
1030      * @param top       the top offset of the new area to be made visible
1031      * @param bottom    the bottom offset of the new area to be made visible
1032      * @return true if the key event is consumed by this method, false otherwise
1033      */
1034     private boolean scrollAndFocus(int direction, int top, int bottom) {
1035         boolean handled = true;
1036
1037         int height = getHeight();
1038         int containerTop = getScrollY();
1039         int containerBottom = containerTop + height;
1040         boolean up = direction == View.FOCUS_UP;
1041
1042         View newFocused = findFocusableViewInBounds(up, top, bottom);
1043         if (newFocused == null) {
1044             newFocused = this;
1045         }
1046
1047         if (top >= containerTop && bottom <= containerBottom) {
1048             handled = false;
1049         } else {
1050             int delta = up ? (top - containerTop) : (bottom - containerBottom);
1051             doScrollY(delta);
1052         }
1053
1054         if (newFocused != findFocus()) newFocused.requestFocus(direction);
1055
1056         return handled;
1057     }
1058
1059     /**
1060      * Handle scrolling in response to an up or down arrow click.
1061      *
1062      * @param direction The direction corresponding to the arrow key that was
1063      *                  pressed
1064      * @return True if we consumed the event, false otherwise
1065      */
1066     public boolean arrowScroll(int direction) {
1067
1068         View currentFocused = findFocus();
1069         if (currentFocused == this) currentFocused = null;
1070
1071         View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
1072
1073         final int maxJump = getMaxScrollAmount();
1074
1075         if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) {
1076             nextFocused.getDrawingRect(mTempRect);
1077             offsetDescendantRectToMyCoords(nextFocused, mTempRect);
1078             int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1079             doScrollY(scrollDelta);
1080             nextFocused.requestFocus(direction);
1081         } else {
1082             // no new focus
1083             int scrollDelta = maxJump;
1084
1085             if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
1086                 scrollDelta = getScrollY();
1087             } else if (direction == View.FOCUS_DOWN) {
1088                 if (getChildCount() > 0) {
1089                     int daBottom = getChildAt(0).getBottom();
1090                     int screenBottom = getScrollY() + getHeight() - mPaddingBottom;
1091                     if (daBottom - screenBottom < maxJump) {
1092                         scrollDelta = daBottom - screenBottom;
1093                     }
1094                 }
1095             }
1096             if (scrollDelta == 0) {
1097                 return false;
1098             }
1099             doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta);
1100         }
1101
1102         if (currentFocused != null && currentFocused.isFocused()
1103                 && isOffScreen(currentFocused)) {
1104             // previously focused item still has focus and is off screen, give
1105             // it up (take it back to ourselves)
1106             // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
1107             // sure to
1108             // get it)
1109             final int descendantFocusability = getDescendantFocusability();  // save
1110             setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
1111             requestFocus();
1112             setDescendantFocusability(descendantFocusability);  // restore
1113         }
1114         return true;
1115     }
1116
1117     /**
1118      * @return whether the descendant of this scroll view is scrolled off
1119      *  screen.
1120      */
1121     private boolean isOffScreen(View descendant) {
1122         return !isWithinDeltaOfScreen(descendant, 0, getHeight());
1123     }
1124
1125     /**
1126      * @return whether the descendant of this scroll view is within delta
1127      *  pixels of being on the screen.
1128      */
1129     private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) {
1130         descendant.getDrawingRect(mTempRect);
1131         offsetDescendantRectToMyCoords(descendant, mTempRect);
1132
1133         return (mTempRect.bottom + delta) >= getScrollY()
1134                 && (mTempRect.top - delta) <= (getScrollY() + height);
1135     }
1136
1137     /**
1138      * Smooth scroll by a Y delta
1139      *
1140      * @param delta the number of pixels to scroll by on the Y axis
1141      */
1142     private void doScrollY(int delta) {
1143         if (delta != 0) {
1144             if (mSmoothScrollingEnabled) {
1145                 smoothScrollBy(0, delta);
1146             } else {
1147                 scrollBy(0, delta);
1148             }
1149         }
1150     }
1151
1152     /**
1153      * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
1154      *
1155      * @param dx the number of pixels to scroll by on the X axis
1156      * @param dy the number of pixels to scroll by on the Y axis
1157      */
1158     public final void smoothScrollBy(int dx, int dy) {
1159         if (getChildCount() == 0) {
1160             // Nothing to do.
1161             return;
1162         }
1163         long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
1164         if (duration > ANIMATED_SCROLL_GAP) {
1165             final int height = getHeight() - mPaddingBottom - mPaddingTop;
1166             final int bottom = getChildAt(0).getHeight();
1167             final int maxY = Math.max(0, bottom - height);
1168             final int scrollY = mScrollY;
1169             dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
1170
1171             mScroller.startScroll(mScrollX, scrollY, 0, dy);
1172             postInvalidateOnAnimation();
1173         } else {
1174             if (!mScroller.isFinished()) {
1175                 mScroller.abortAnimation();
1176                 if (mFlingStrictSpan != null) {
1177                     mFlingStrictSpan.finish();
1178                     mFlingStrictSpan = null;
1179                 }
1180             }
1181             scrollBy(dx, dy);
1182         }
1183         mLastScroll = AnimationUtils.currentAnimationTimeMillis();
1184     }
1185
1186     /**
1187      * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
1188      *
1189      * @param x the position where to scroll on the X axis
1190      * @param y the position where to scroll on the Y axis
1191      */
1192     public final void smoothScrollTo(int x, int y) {
1193         smoothScrollBy(x - mScrollX, y - mScrollY);
1194     }
1195
1196     /**
1197      * <p>The scroll range of a scroll view is the overall height of all of its
1198      * children.</p>
1199      */
1200     @Override
1201     protected int computeVerticalScrollRange() {
1202         final int count = getChildCount();
1203         final int contentHeight = getHeight() - mPaddingBottom - mPaddingTop;
1204         if (count == 0) {
1205             return contentHeight;
1206         }
1207
1208         int scrollRange = getChildAt(0).getBottom();
1209         final int scrollY = mScrollY;
1210         final int overscrollBottom = Math.max(0, scrollRange - contentHeight);
1211         if (scrollY < 0) {
1212             scrollRange -= scrollY;
1213         } else if (scrollY > overscrollBottom) {
1214             scrollRange += scrollY - overscrollBottom;
1215         }
1216
1217         return scrollRange;
1218     }
1219
1220     @Override
1221     protected int computeVerticalScrollOffset() {
1222         return Math.max(0, super.computeVerticalScrollOffset());
1223     }
1224
1225     @Override
1226     protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
1227         ViewGroup.LayoutParams lp = child.getLayoutParams();
1228
1229         int childWidthMeasureSpec;
1230         int childHeightMeasureSpec;
1231
1232         childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft
1233                 + mPaddingRight, lp.width);
1234
1235         childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1236
1237         child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1238     }
1239
1240     @Override
1241     protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
1242             int parentHeightMeasureSpec, int heightUsed) {
1243         final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
1244
1245         final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
1246                 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
1247                         + widthUsed, lp.width);
1248         final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
1249                 lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);
1250
1251         child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1252     }
1253
1254     @Override
1255     public void computeScroll() {
1256         if (mScroller.computeScrollOffset()) {
1257             // This is called at drawing time by ViewGroup.  We don't want to
1258             // re-show the scrollbars at this point, which scrollTo will do,
1259             // so we replicate most of scrollTo here.
1260             //
1261             //         It's a little odd to call onScrollChanged from inside the drawing.
1262             //
1263             //         It is, except when you remember that computeScroll() is used to
1264             //         animate scrolling. So unless we want to defer the onScrollChanged()
1265             //         until the end of the animated scrolling, we don't really have a
1266             //         choice here.
1267             //
1268             //         I agree.  The alternative, which I think would be worse, is to post
1269             //         something and tell the subclasses later.  This is bad because there
1270             //         will be a window where mScrollX/Y is different from what the app
1271             //         thinks it is.
1272             //
1273             int oldX = mScrollX;
1274             int oldY = mScrollY;
1275             int x = mScroller.getCurrX();
1276             int y = mScroller.getCurrY();
1277
1278             if (oldX != x || oldY != y) {
1279                 final int range = getScrollRange();
1280                 final int overscrollMode = getOverScrollMode();
1281                 final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS ||
1282                         (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0);
1283
1284                 overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, range,
1285                         0, mOverflingDistance, false);
1286                 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
1287
1288                 if (canOverscroll) {
1289                     if (y < 0 && oldY >= 0) {
1290                         mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity());
1291                     } else if (y > range && oldY <= range) {
1292                         mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity());
1293                     }
1294                 }
1295             }
1296
1297             if (!awakenScrollBars()) {
1298                 // Keep on drawing until the animation has finished.
1299                 postInvalidateOnAnimation();
1300             }
1301         } else {
1302             if (mFlingStrictSpan != null) {
1303                 mFlingStrictSpan.finish();
1304                 mFlingStrictSpan = null;
1305             }
1306         }
1307     }
1308
1309     /**
1310      * Scrolls the view to the given child.
1311      *
1312      * @param child the View to scroll to
1313      */
1314     private void scrollToChild(View child) {
1315         child.getDrawingRect(mTempRect);
1316
1317         /* Offset from child's local coordinates to ScrollView coordinates */
1318         offsetDescendantRectToMyCoords(child, mTempRect);
1319
1320         int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1321
1322         if (scrollDelta != 0) {
1323             scrollBy(0, scrollDelta);
1324         }
1325     }
1326
1327     /**
1328      * If rect is off screen, scroll just enough to get it (or at least the
1329      * first screen size chunk of it) on screen.
1330      *
1331      * @param rect      The rectangle.
1332      * @param immediate True to scroll immediately without animation
1333      * @return true if scrolling was performed
1334      */
1335     private boolean scrollToChildRect(Rect rect, boolean immediate) {
1336         final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
1337         final boolean scroll = delta != 0;
1338         if (scroll) {
1339             if (immediate) {
1340                 scrollBy(0, delta);
1341             } else {
1342                 smoothScrollBy(0, delta);
1343             }
1344         }
1345         return scroll;
1346     }
1347
1348     /**
1349      * Compute the amount to scroll in the Y direction in order to get
1350      * a rectangle completely on the screen (or, if taller than the screen,
1351      * at least the first screen size chunk of it).
1352      *
1353      * @param rect The rect.
1354      * @return The scroll delta.
1355      */
1356     protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
1357         if (getChildCount() == 0) return 0;
1358
1359         int height = getHeight();
1360         int screenTop = getScrollY();
1361         int screenBottom = screenTop + height;
1362
1363         int fadingEdge = getVerticalFadingEdgeLength();
1364
1365         // leave room for top fading edge as long as rect isn't at very top
1366         if (rect.top > 0) {
1367             screenTop += fadingEdge;
1368         }
1369
1370         // leave room for bottom fading edge as long as rect isn't at very bottom
1371         if (rect.bottom < getChildAt(0).getHeight()) {
1372             screenBottom -= fadingEdge;
1373         }
1374
1375         int scrollYDelta = 0;
1376
1377         if (rect.bottom > screenBottom && rect.top > screenTop) {
1378             // need to move down to get it in view: move down just enough so
1379             // that the entire rectangle is in view (or at least the first
1380             // screen size chunk).
1381
1382             if (rect.height() > height) {
1383                 // just enough to get screen size chunk on
1384                 scrollYDelta += (rect.top - screenTop);
1385             } else {
1386                 // get entire rect at bottom of screen
1387                 scrollYDelta += (rect.bottom - screenBottom);
1388             }
1389
1390             // make sure we aren't scrolling beyond the end of our content
1391             int bottom = getChildAt(0).getBottom();
1392             int distanceToBottom = bottom - screenBottom;
1393             scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
1394
1395         } else if (rect.top < screenTop && rect.bottom < screenBottom) {
1396             // need to move up to get it in view: move up just enough so that
1397             // entire rectangle is in view (or at least the first screen
1398             // size chunk of it).
1399
1400             if (rect.height() > height) {
1401                 // screen size chunk
1402                 scrollYDelta -= (screenBottom - rect.bottom);
1403             } else {
1404                 // entire rect at top
1405                 scrollYDelta -= (screenTop - rect.top);
1406             }
1407
1408             // make sure we aren't scrolling any further than the top our content
1409             scrollYDelta = Math.max(scrollYDelta, -getScrollY());
1410         }
1411         return scrollYDelta;
1412     }
1413
1414     @Override
1415     public void requestChildFocus(View child, View focused) {
1416         if (!mIsLayoutDirty) {
1417             scrollToChild(focused);
1418         } else {
1419             // The child may not be laid out yet, we can't compute the scroll yet
1420             mChildToScrollTo = focused;
1421         }
1422         super.requestChildFocus(child, focused);
1423     }
1424
1425
1426     /**
1427      * When looking for focus in children of a scroll view, need to be a little
1428      * more careful not to give focus to something that is scrolled off screen.
1429      *
1430      * This is more expensive than the default {@link android.view.ViewGroup}
1431      * implementation, otherwise this behavior might have been made the default.
1432      */
1433     @Override
1434     protected boolean onRequestFocusInDescendants(int direction,
1435             Rect previouslyFocusedRect) {
1436
1437         // convert from forward / backward notation to up / down / left / right
1438         // (ugh).
1439         if (direction == View.FOCUS_FORWARD) {
1440             direction = View.FOCUS_DOWN;
1441         } else if (direction == View.FOCUS_BACKWARD) {
1442             direction = View.FOCUS_UP;
1443         }
1444
1445         final View nextFocus = previouslyFocusedRect == null ?
1446                 FocusFinder.getInstance().findNextFocus(this, null, direction) :
1447                 FocusFinder.getInstance().findNextFocusFromRect(this,
1448                         previouslyFocusedRect, direction);
1449
1450         if (nextFocus == null) {
1451             return false;
1452         }
1453
1454         if (isOffScreen(nextFocus)) {
1455             return false;
1456         }
1457
1458         return nextFocus.requestFocus(direction, previouslyFocusedRect);
1459     }
1460
1461     @Override
1462     public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1463             boolean immediate) {
1464         // offset into coordinate space of this scroll view
1465         rectangle.offset(child.getLeft() - child.getScrollX(),
1466                 child.getTop() - child.getScrollY());
1467
1468         return scrollToChildRect(rectangle, immediate);
1469     }
1470
1471     @Override
1472     public void requestLayout() {
1473         mIsLayoutDirty = true;
1474         super.requestLayout();
1475     }
1476
1477     @Override
1478     protected void onDetachedFromWindow() {
1479         super.onDetachedFromWindow();
1480
1481         if (mScrollStrictSpan != null) {
1482             mScrollStrictSpan.finish();
1483             mScrollStrictSpan = null;
1484         }
1485         if (mFlingStrictSpan != null) {
1486             mFlingStrictSpan.finish();
1487             mFlingStrictSpan = null;
1488         }
1489     }
1490
1491     @Override
1492     protected void onLayout(boolean changed, int l, int t, int r, int b) {
1493         super.onLayout(changed, l, t, r, b);
1494         mIsLayoutDirty = false;
1495         // Give a child focus if it needs it
1496         if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1497             scrollToChild(mChildToScrollTo);
1498         }
1499         mChildToScrollTo = null;
1500
1501         if (!isLaidOut()) {
1502             if (mSavedState != null) {
1503                 mScrollY = mSavedState.scrollPosition;
1504                 mSavedState = null;
1505             } // mScrollY default value is "0"
1506
1507             final int childHeight = (getChildCount() > 0) ? getChildAt(0).getMeasuredHeight() : 0;
1508             final int scrollRange = Math.max(0,
1509                     childHeight - (b - t - mPaddingBottom - mPaddingTop));
1510
1511             // Don't forget to clamp
1512             if (mScrollY > scrollRange) {
1513                 mScrollY = scrollRange;
1514             } else if (mScrollY < 0) {
1515                 mScrollY = 0;
1516             }
1517         }
1518
1519         // Calling this with the present values causes it to re-claim them
1520         scrollTo(mScrollX, mScrollY);
1521     }
1522
1523     @Override
1524     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1525         super.onSizeChanged(w, h, oldw, oldh);
1526
1527         View currentFocused = findFocus();
1528         if (null == currentFocused || this == currentFocused)
1529             return;
1530
1531         // If the currently-focused view was visible on the screen when the
1532         // screen was at the old height, then scroll the screen to make that
1533         // view visible with the new screen height.
1534         if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) {
1535             currentFocused.getDrawingRect(mTempRect);
1536             offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1537             int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1538             doScrollY(scrollDelta);
1539         }
1540     }
1541
1542     /**
1543      * Return true if child is a descendant of parent, (or equal to the parent).
1544      */
1545     private static boolean isViewDescendantOf(View child, View parent) {
1546         if (child == parent) {
1547             return true;
1548         }
1549
1550         final ViewParent theParent = child.getParent();
1551         return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1552     }
1553
1554     /**
1555      * Fling the scroll view
1556      *
1557      * @param velocityY The initial velocity in the Y direction. Positive
1558      *                  numbers mean that the finger/cursor is moving down the screen,
1559      *                  which means we want to scroll towards the top.
1560      */
1561     public void fling(int velocityY) {
1562         if (getChildCount() > 0) {
1563             int height = getHeight() - mPaddingBottom - mPaddingTop;
1564             int bottom = getChildAt(0).getHeight();
1565
1566             mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0,
1567                     Math.max(0, bottom - height), 0, height/2);
1568
1569             if (mFlingStrictSpan == null) {
1570                 mFlingStrictSpan = StrictMode.enterCriticalSpan("ScrollView-fling");
1571             }
1572
1573             postInvalidateOnAnimation();
1574         }
1575     }
1576
1577     private void flingWithNestedDispatch(int velocityY) {
1578         final boolean canFling = (mScrollY > 0 || velocityY > 0) &&
1579                 (mScrollY < getScrollRange() || velocityY < 0);
1580         if (!dispatchNestedPreFling(0, velocityY)) {
1581             dispatchNestedFling(0, velocityY, canFling);
1582             if (canFling) {
1583                 fling(velocityY);
1584             }
1585         }
1586     }
1587
1588     private void endDrag() {
1589         mIsBeingDragged = false;
1590
1591         recycleVelocityTracker();
1592
1593         if (mEdgeGlowTop != null) {
1594             mEdgeGlowTop.onRelease();
1595             mEdgeGlowBottom.onRelease();
1596         }
1597
1598         if (mScrollStrictSpan != null) {
1599             mScrollStrictSpan.finish();
1600             mScrollStrictSpan = null;
1601         }
1602     }
1603
1604     /**
1605      * {@inheritDoc}
1606      *
1607      * <p>This version also clamps the scrolling to the bounds of our child.
1608      */
1609     @Override
1610     public void scrollTo(int x, int y) {
1611         // we rely on the fact the View.scrollBy calls scrollTo.
1612         if (getChildCount() > 0) {
1613             View child = getChildAt(0);
1614             x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1615             y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1616             if (x != mScrollX || y != mScrollY) {
1617                 super.scrollTo(x, y);
1618             }
1619         }
1620     }
1621
1622     @Override
1623     public void setOverScrollMode(int mode) {
1624         if (mode != OVER_SCROLL_NEVER) {
1625             if (mEdgeGlowTop == null) {
1626                 Context context = getContext();
1627                 mEdgeGlowTop = new EdgeEffect(context);
1628                 mEdgeGlowBottom = new EdgeEffect(context);
1629             }
1630         } else {
1631             mEdgeGlowTop = null;
1632             mEdgeGlowBottom = null;
1633         }
1634         super.setOverScrollMode(mode);
1635     }
1636
1637     @Override
1638     public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
1639         return (nestedScrollAxes & SCROLL_AXIS_VERTICAL) != 0;
1640     }
1641
1642     @Override
1643     public void onNestedScrollAccepted(View child, View target, int axes) {
1644         super.onNestedScrollAccepted(child, target, axes);
1645         startNestedScroll(SCROLL_AXIS_VERTICAL);
1646     }
1647
1648     /**
1649      * @inheritDoc
1650      */
1651     @Override
1652     public void onStopNestedScroll(View target) {
1653         super.onStopNestedScroll(target);
1654     }
1655
1656     @Override
1657     public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
1658             int dxUnconsumed, int dyUnconsumed) {
1659         final int oldScrollY = mScrollY;
1660         scrollBy(0, dyUnconsumed);
1661         final int myConsumed = mScrollY - oldScrollY;
1662         final int myUnconsumed = dyUnconsumed - myConsumed;
1663         dispatchNestedScroll(0, myConsumed, 0, myUnconsumed, null);
1664     }
1665
1666     /**
1667      * @inheritDoc
1668      */
1669     @Override
1670     public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
1671         if (!consumed) {
1672             flingWithNestedDispatch((int) velocityY);
1673             return true;
1674         }
1675         return false;
1676     }
1677
1678     @Override
1679     public void draw(Canvas canvas) {
1680         super.draw(canvas);
1681         if (mEdgeGlowTop != null) {
1682             final int scrollY = mScrollY;
1683             if (!mEdgeGlowTop.isFinished()) {
1684                 final int restoreCount = canvas.save();
1685                 final int width = getWidth() - mPaddingLeft - mPaddingRight;
1686
1687                 canvas.translate(mPaddingLeft, Math.min(0, scrollY));
1688                 mEdgeGlowTop.setSize(width, getHeight());
1689                 if (mEdgeGlowTop.draw(canvas)) {
1690                     postInvalidateOnAnimation();
1691                 }
1692                 canvas.restoreToCount(restoreCount);
1693             }
1694             if (!mEdgeGlowBottom.isFinished()) {
1695                 final int restoreCount = canvas.save();
1696                 final int width = getWidth() - mPaddingLeft - mPaddingRight;
1697                 final int height = getHeight();
1698
1699                 canvas.translate(-width + mPaddingLeft,
1700                         Math.max(getScrollRange(), scrollY) + height);
1701                 canvas.rotate(180, width, 0);
1702                 mEdgeGlowBottom.setSize(width, height);
1703                 if (mEdgeGlowBottom.draw(canvas)) {
1704                     postInvalidateOnAnimation();
1705                 }
1706                 canvas.restoreToCount(restoreCount);
1707             }
1708         }
1709     }
1710
1711     private static int clamp(int n, int my, int child) {
1712         if (my >= child || n < 0) {
1713             /* my >= child is this case:
1714              *                    |--------------- me ---------------|
1715              *     |------ child ------|
1716              * or
1717              *     |--------------- me ---------------|
1718              *            |------ child ------|
1719              * or
1720              *     |--------------- me ---------------|
1721              *                                  |------ child ------|
1722              *
1723              * n < 0 is this case:
1724              *     |------ me ------|
1725              *                    |-------- child --------|
1726              *     |-- mScrollX --|
1727              */
1728             return 0;
1729         }
1730         if ((my+n) > child) {
1731             /* this case:
1732              *                    |------ me ------|
1733              *     |------ child ------|
1734              *     |-- mScrollX --|
1735              */
1736             return child-my;
1737         }
1738         return n;
1739     }
1740
1741     @Override
1742     protected void onRestoreInstanceState(Parcelable state) {
1743         if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1744             // Some old apps reused IDs in ways they shouldn't have.
1745             // Don't break them, but they don't get scroll state restoration.
1746             super.onRestoreInstanceState(state);
1747             return;
1748         }
1749         SavedState ss = (SavedState) state;
1750         super.onRestoreInstanceState(ss.getSuperState());
1751         mSavedState = ss;
1752         requestLayout();
1753     }
1754
1755     @Override
1756     protected Parcelable onSaveInstanceState() {
1757         if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1758             // Some old apps reused IDs in ways they shouldn't have.
1759             // Don't break them, but they don't get scroll state restoration.
1760             return super.onSaveInstanceState();
1761         }
1762         Parcelable superState = super.onSaveInstanceState();
1763         SavedState ss = new SavedState(superState);
1764         ss.scrollPosition = mScrollY;
1765         return ss;
1766     }
1767
1768     static class SavedState extends BaseSavedState {
1769         public int scrollPosition;
1770
1771         SavedState(Parcelable superState) {
1772             super(superState);
1773         }
1774
1775         public SavedState(Parcel source) {
1776             super(source);
1777             scrollPosition = source.readInt();
1778         }
1779
1780         @Override
1781         public void writeToParcel(Parcel dest, int flags) {
1782             super.writeToParcel(dest, flags);
1783             dest.writeInt(scrollPosition);
1784         }
1785
1786         @Override
1787         public String toString() {
1788             return "HorizontalScrollView.SavedState{"
1789                     + Integer.toHexString(System.identityHashCode(this))
1790                     + " scrollPosition=" + scrollPosition + "}";
1791         }
1792
1793         public static final Parcelable.Creator<SavedState> CREATOR
1794                 = new Parcelable.Creator<SavedState>() {
1795             public SavedState createFromParcel(Parcel in) {
1796                 return new SavedState(in);
1797             }
1798
1799             public SavedState[] newArray(int size) {
1800                 return new SavedState[size];
1801             }
1802         };
1803     }
1804
1805 }