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