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