HorizontalScrollView.java revision 9bc30d31322848d61f518c1db43544988faaba8f
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_DOWN: {
479                final int index = ev.getActionIndex();
480                final float x = ev.getX(index);
481                mLastMotionX = x;
482                mActivePointerId = ev.getPointerId(index);
483                break;
484            }
485            case MotionEvent.ACTION_POINTER_UP:
486                onSecondaryPointerUp(ev);
487                mLastMotionX = ev.getX(ev.findPointerIndex(mActivePointerId));
488                break;
489        }
490
491        /*
492        * The only time we want to intercept motion events is if we are in the
493        * drag mode.
494        */
495        return mIsBeingDragged;
496    }
497
498    @Override
499    public boolean onTouchEvent(MotionEvent ev) {
500
501        if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
502            // Don't handle edge touches immediately -- they may actually belong to one of our
503            // descendants.
504            return false;
505        }
506
507        if (mVelocityTracker == null) {
508            mVelocityTracker = VelocityTracker.obtain();
509        }
510        mVelocityTracker.addMovement(ev);
511
512        final int action = ev.getAction();
513
514        switch (action & MotionEvent.ACTION_MASK) {
515            case MotionEvent.ACTION_DOWN: {
516                mIsBeingDragged = getChildCount() != 0;
517                if (!mIsBeingDragged) {
518                    return false;
519                }
520
521                /*
522                 * If being flinged and user touches, stop the fling. isFinished
523                 * will be false if being flinged.
524                 */
525                if (!mScroller.isFinished()) {
526                    mScroller.abortAnimation();
527                }
528
529                // Remember where the motion event started
530                mLastMotionX = ev.getX();
531                mActivePointerId = ev.getPointerId(0);
532                break;
533            }
534            case MotionEvent.ACTION_MOVE:
535                if (mIsBeingDragged) {
536                    // Scroll to follow the motion event
537                    final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
538                    final float x = ev.getX(activePointerIndex);
539                    final int deltaX = (int) (mLastMotionX - x);
540                    mLastMotionX = x;
541
542                    final int oldX = mScrollX;
543                    final int oldY = mScrollY;
544                    final int range = getScrollRange();
545                    if (overScrollBy(deltaX, 0, mScrollX, 0, range, 0,
546                            mOverscrollDistance, 0, true)) {
547                        // Break our velocity if we hit a scroll barrier.
548                        mVelocityTracker.clear();
549                    }
550                    onScrollChanged(mScrollX, mScrollY, oldX, oldY);
551
552                    final int overscrollMode = getOverScrollMode();
553                    if (overscrollMode == OVER_SCROLL_ALWAYS ||
554                            (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0)) {
555                        final int pulledToX = oldX + deltaX;
556                        if (pulledToX < 0) {
557                            mEdgeGlowLeft.onPull((float) deltaX / getWidth());
558                            if (!mEdgeGlowRight.isFinished()) {
559                                mEdgeGlowRight.onRelease();
560                            }
561                        } else if (pulledToX > range) {
562                            mEdgeGlowRight.onPull((float) deltaX / getWidth());
563                            if (!mEdgeGlowLeft.isFinished()) {
564                                mEdgeGlowLeft.onRelease();
565                            }
566                        }
567                        if (mEdgeGlowLeft != null
568                                && (!mEdgeGlowLeft.isFinished() || !mEdgeGlowRight.isFinished())) {
569                            invalidate();
570                        }
571                    }
572                }
573                break;
574            case MotionEvent.ACTION_UP:
575                if (mIsBeingDragged) {
576                    final VelocityTracker velocityTracker = mVelocityTracker;
577                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
578                    int initialVelocity = (int) velocityTracker.getXVelocity(mActivePointerId);
579
580                    if (getChildCount() > 0) {
581                        if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
582                            fling(-initialVelocity);
583                        } else {
584                            final int right = getScrollRange();
585                            if (mScroller.springBack(mScrollX, mScrollY, 0, right, 0, 0)) {
586                                invalidate();
587                            }
588                        }
589                    }
590
591                    mActivePointerId = INVALID_POINTER;
592                    mIsBeingDragged = false;
593
594                    if (mVelocityTracker != null) {
595                        mVelocityTracker.recycle();
596                        mVelocityTracker = null;
597                    }
598                    if (mEdgeGlowLeft != null) {
599                        mEdgeGlowLeft.onRelease();
600                        mEdgeGlowRight.onRelease();
601                    }
602                }
603                break;
604            case MotionEvent.ACTION_CANCEL:
605                if (mIsBeingDragged && getChildCount() > 0) {
606                    if (mScroller.springBack(mScrollX, mScrollY, 0, getScrollRange(), 0, 0)) {
607                        invalidate();
608                    }
609                    mActivePointerId = INVALID_POINTER;
610                    mIsBeingDragged = false;
611                    if (mVelocityTracker != null) {
612                        mVelocityTracker.recycle();
613                        mVelocityTracker = null;
614                    }
615                    if (mEdgeGlowLeft != null) {
616                        mEdgeGlowLeft.onRelease();
617                        mEdgeGlowRight.onRelease();
618                    }
619                }
620                break;
621            case MotionEvent.ACTION_POINTER_UP:
622                onSecondaryPointerUp(ev);
623                break;
624        }
625        return true;
626    }
627
628    private void onSecondaryPointerUp(MotionEvent ev) {
629        final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
630                MotionEvent.ACTION_POINTER_INDEX_SHIFT;
631        final int pointerId = ev.getPointerId(pointerIndex);
632        if (pointerId == mActivePointerId) {
633            // This was our active pointer going up. Choose a new
634            // active pointer and adjust accordingly.
635            // TODO: Make this decision more intelligent.
636            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
637            mLastMotionX = ev.getX(newPointerIndex);
638            mActivePointerId = ev.getPointerId(newPointerIndex);
639            if (mVelocityTracker != null) {
640                mVelocityTracker.clear();
641            }
642        }
643    }
644
645    @Override
646    public boolean onGenericMotionEvent(MotionEvent event) {
647        if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
648            switch (event.getAction()) {
649                case MotionEvent.ACTION_SCROLL: {
650                    if (!mIsBeingDragged) {
651                        final float hscroll;
652                        if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
653                            hscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
654                        } else {
655                            hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
656                        }
657                        if (hscroll != 0) {
658                            final int delta = (int) (hscroll * getHorizontalScrollFactor());
659                            final int range = getScrollRange();
660                            int oldScrollX = mScrollX;
661                            int newScrollX = oldScrollX + delta;
662                            if (newScrollX < 0) {
663                                newScrollX = 0;
664                            } else if (newScrollX > range) {
665                                newScrollX = range;
666                            }
667                            if (newScrollX != oldScrollX) {
668                                super.scrollTo(newScrollX, mScrollY);
669                                return true;
670                            }
671                        }
672                    }
673                }
674            }
675        }
676        return super.onGenericMotionEvent(event);
677    }
678
679    @Override
680    protected void onOverScrolled(int scrollX, int scrollY,
681            boolean clampedX, boolean clampedY) {
682        // Treat animating scrolls differently; see #computeScroll() for why.
683        if (!mScroller.isFinished()) {
684            mScrollX = scrollX;
685            mScrollY = scrollY;
686            invalidateParentIfNeeded();
687            if (clampedX) {
688                mScroller.springBack(mScrollX, mScrollY, 0, getScrollRange(), 0, 0);
689            }
690        } else {
691            super.scrollTo(scrollX, scrollY);
692        }
693        awakenScrollBars();
694    }
695
696    private int getScrollRange() {
697        int scrollRange = 0;
698        if (getChildCount() > 0) {
699            View child = getChildAt(0);
700            scrollRange = Math.max(0,
701                    child.getWidth() - (getWidth() - mPaddingLeft - mPaddingRight));
702        }
703        return scrollRange;
704    }
705
706    /**
707     * <p>
708     * Finds the next focusable component that fits in this View's bounds
709     * (excluding fading edges) pretending that this View's left is located at
710     * the parameter left.
711     * </p>
712     *
713     * @param leftFocus          look for a candidate is the one at the left of the bounds
714     *                           if leftFocus is true, or at the right of the bounds if leftFocus
715     *                           is false
716     * @param left               the left offset of the bounds in which a focusable must be
717     *                           found (the fading edge is assumed to start at this position)
718     * @param preferredFocusable the View that has highest priority and will be
719     *                           returned if it is within my bounds (null is valid)
720     * @return the next focusable component in the bounds or null if none can be found
721     */
722    private View findFocusableViewInMyBounds(final boolean leftFocus,
723            final int left, View preferredFocusable) {
724        /*
725         * The fading edge's transparent side should be considered for focus
726         * since it's mostly visible, so we divide the actual fading edge length
727         * by 2.
728         */
729        final int fadingEdgeLength = getHorizontalFadingEdgeLength() / 2;
730        final int leftWithoutFadingEdge = left + fadingEdgeLength;
731        final int rightWithoutFadingEdge = left + getWidth() - fadingEdgeLength;
732
733        if ((preferredFocusable != null)
734                && (preferredFocusable.getLeft() < rightWithoutFadingEdge)
735                && (preferredFocusable.getRight() > leftWithoutFadingEdge)) {
736            return preferredFocusable;
737        }
738
739        return findFocusableViewInBounds(leftFocus, leftWithoutFadingEdge,
740                rightWithoutFadingEdge);
741    }
742
743    /**
744     * <p>
745     * Finds the next focusable component that fits in the specified bounds.
746     * </p>
747     *
748     * @param leftFocus look for a candidate is the one at the left of the bounds
749     *                  if leftFocus is true, or at the right of the bounds if
750     *                  leftFocus is false
751     * @param left      the left offset of the bounds in which a focusable must be
752     *                  found
753     * @param right     the right offset of the bounds in which a focusable must
754     *                  be found
755     * @return the next focusable component in the bounds or null if none can
756     *         be found
757     */
758    private View findFocusableViewInBounds(boolean leftFocus, int left, int right) {
759
760        List<View> focusables = getFocusables(View.FOCUS_FORWARD);
761        View focusCandidate = null;
762
763        /*
764         * A fully contained focusable is one where its left is below the bound's
765         * left, and its right is above the bound's right. A partially
766         * contained focusable is one where some part of it is within the
767         * bounds, but it also has some part that is not within bounds.  A fully contained
768         * focusable is preferred to a partially contained focusable.
769         */
770        boolean foundFullyContainedFocusable = false;
771
772        int count = focusables.size();
773        for (int i = 0; i < count; i++) {
774            View view = focusables.get(i);
775            int viewLeft = view.getLeft();
776            int viewRight = view.getRight();
777
778            if (left < viewRight && viewLeft < right) {
779                /*
780                 * the focusable is in the target area, it is a candidate for
781                 * focusing
782                 */
783
784                final boolean viewIsFullyContained = (left < viewLeft) &&
785                        (viewRight < right);
786
787                if (focusCandidate == null) {
788                    /* No candidate, take this one */
789                    focusCandidate = view;
790                    foundFullyContainedFocusable = viewIsFullyContained;
791                } else {
792                    final boolean viewIsCloserToBoundary =
793                            (leftFocus && viewLeft < focusCandidate.getLeft()) ||
794                                    (!leftFocus && viewRight > focusCandidate.getRight());
795
796                    if (foundFullyContainedFocusable) {
797                        if (viewIsFullyContained && viewIsCloserToBoundary) {
798                            /*
799                             * We're dealing with only fully contained views, so
800                             * it has to be closer to the boundary to beat our
801                             * candidate
802                             */
803                            focusCandidate = view;
804                        }
805                    } else {
806                        if (viewIsFullyContained) {
807                            /* Any fully contained view beats a partially contained view */
808                            focusCandidate = view;
809                            foundFullyContainedFocusable = true;
810                        } else if (viewIsCloserToBoundary) {
811                            /*
812                             * Partially contained view beats another partially
813                             * contained view if it's closer
814                             */
815                            focusCandidate = view;
816                        }
817                    }
818                }
819            }
820        }
821
822        return focusCandidate;
823    }
824
825    /**
826     * <p>Handles scrolling in response to a "page up/down" shortcut press. This
827     * method will scroll the view by one page left or right and give the focus
828     * to the leftmost/rightmost component in the new visible area. If no
829     * component is a good candidate for focus, this scrollview reclaims the
830     * focus.</p>
831     *
832     * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT}
833     *                  to go one page left or {@link android.view.View#FOCUS_RIGHT}
834     *                  to go one page right
835     * @return true if the key event is consumed by this method, false otherwise
836     */
837    public boolean pageScroll(int direction) {
838        boolean right = direction == View.FOCUS_RIGHT;
839        int width = getWidth();
840
841        if (right) {
842            mTempRect.left = getScrollX() + width;
843            int count = getChildCount();
844            if (count > 0) {
845                View view = getChildAt(0);
846                if (mTempRect.left + width > view.getRight()) {
847                    mTempRect.left = view.getRight() - width;
848                }
849            }
850        } else {
851            mTempRect.left = getScrollX() - width;
852            if (mTempRect.left < 0) {
853                mTempRect.left = 0;
854            }
855        }
856        mTempRect.right = mTempRect.left + width;
857
858        return scrollAndFocus(direction, mTempRect.left, mTempRect.right);
859    }
860
861    /**
862     * <p>Handles scrolling in response to a "home/end" shortcut press. This
863     * method will scroll the view to the left or right and give the focus
864     * to the leftmost/rightmost component in the new visible area. If no
865     * component is a good candidate for focus, this scrollview reclaims the
866     * focus.</p>
867     *
868     * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT}
869     *                  to go the left of the view or {@link android.view.View#FOCUS_RIGHT}
870     *                  to go the right
871     * @return true if the key event is consumed by this method, false otherwise
872     */
873    public boolean fullScroll(int direction) {
874        boolean right = direction == View.FOCUS_RIGHT;
875        int width = getWidth();
876
877        mTempRect.left = 0;
878        mTempRect.right = width;
879
880        if (right) {
881            int count = getChildCount();
882            if (count > 0) {
883                View view = getChildAt(0);
884                mTempRect.right = view.getRight();
885                mTempRect.left = mTempRect.right - width;
886            }
887        }
888
889        return scrollAndFocus(direction, mTempRect.left, mTempRect.right);
890    }
891
892    /**
893     * <p>Scrolls the view to make the area defined by <code>left</code> and
894     * <code>right</code> visible. This method attempts to give the focus
895     * to a component visible in this area. If no component can be focused in
896     * the new visible area, the focus is reclaimed by this scrollview.</p>
897     *
898     * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT}
899     *                  to go left {@link android.view.View#FOCUS_RIGHT} to right
900     * @param left     the left offset of the new area to be made visible
901     * @param right    the right offset of the new area to be made visible
902     * @return true if the key event is consumed by this method, false otherwise
903     */
904    private boolean scrollAndFocus(int direction, int left, int right) {
905        boolean handled = true;
906
907        int width = getWidth();
908        int containerLeft = getScrollX();
909        int containerRight = containerLeft + width;
910        boolean goLeft = direction == View.FOCUS_LEFT;
911
912        View newFocused = findFocusableViewInBounds(goLeft, left, right);
913        if (newFocused == null) {
914            newFocused = this;
915        }
916
917        if (left >= containerLeft && right <= containerRight) {
918            handled = false;
919        } else {
920            int delta = goLeft ? (left - containerLeft) : (right - containerRight);
921            doScrollX(delta);
922        }
923
924        if (newFocused != findFocus()) newFocused.requestFocus(direction);
925
926        return handled;
927    }
928
929    /**
930     * Handle scrolling in response to a left or right arrow click.
931     *
932     * @param direction The direction corresponding to the arrow key that was
933     *                  pressed
934     * @return True if we consumed the event, false otherwise
935     */
936    public boolean arrowScroll(int direction) {
937
938        View currentFocused = findFocus();
939        if (currentFocused == this) currentFocused = null;
940
941        View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
942
943        final int maxJump = getMaxScrollAmount();
944
945        if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump)) {
946            nextFocused.getDrawingRect(mTempRect);
947            offsetDescendantRectToMyCoords(nextFocused, mTempRect);
948            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
949            doScrollX(scrollDelta);
950            nextFocused.requestFocus(direction);
951        } else {
952            // no new focus
953            int scrollDelta = maxJump;
954
955            if (direction == View.FOCUS_LEFT && getScrollX() < scrollDelta) {
956                scrollDelta = getScrollX();
957            } else if (direction == View.FOCUS_RIGHT && getChildCount() > 0) {
958
959                int daRight = getChildAt(0).getRight();
960
961                int screenRight = getScrollX() + getWidth();
962
963                if (daRight - screenRight < maxJump) {
964                    scrollDelta = daRight - screenRight;
965                }
966            }
967            if (scrollDelta == 0) {
968                return false;
969            }
970            doScrollX(direction == View.FOCUS_RIGHT ? scrollDelta : -scrollDelta);
971        }
972
973        if (currentFocused != null && currentFocused.isFocused()
974                && isOffScreen(currentFocused)) {
975            // previously focused item still has focus and is off screen, give
976            // it up (take it back to ourselves)
977            // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
978            // sure to
979            // get it)
980            final int descendantFocusability = getDescendantFocusability();  // save
981            setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
982            requestFocus();
983            setDescendantFocusability(descendantFocusability);  // restore
984        }
985        return true;
986    }
987
988    /**
989     * @return whether the descendant of this scroll view is scrolled off
990     *  screen.
991     */
992    private boolean isOffScreen(View descendant) {
993        return !isWithinDeltaOfScreen(descendant, 0);
994    }
995
996    /**
997     * @return whether the descendant of this scroll view is within delta
998     *  pixels of being on the screen.
999     */
1000    private boolean isWithinDeltaOfScreen(View descendant, int delta) {
1001        descendant.getDrawingRect(mTempRect);
1002        offsetDescendantRectToMyCoords(descendant, mTempRect);
1003
1004        return (mTempRect.right + delta) >= getScrollX()
1005                && (mTempRect.left - delta) <= (getScrollX() + getWidth());
1006    }
1007
1008    /**
1009     * Smooth scroll by a X delta
1010     *
1011     * @param delta the number of pixels to scroll by on the X axis
1012     */
1013    private void doScrollX(int delta) {
1014        if (delta != 0) {
1015            if (mSmoothScrollingEnabled) {
1016                smoothScrollBy(delta, 0);
1017            } else {
1018                scrollBy(delta, 0);
1019            }
1020        }
1021    }
1022
1023    /**
1024     * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
1025     *
1026     * @param dx the number of pixels to scroll by on the X axis
1027     * @param dy the number of pixels to scroll by on the Y axis
1028     */
1029    public final void smoothScrollBy(int dx, int dy) {
1030        if (getChildCount() == 0) {
1031            // Nothing to do.
1032            return;
1033        }
1034        long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
1035        if (duration > ANIMATED_SCROLL_GAP) {
1036            final int width = getWidth() - mPaddingRight - mPaddingLeft;
1037            final int right = getChildAt(0).getWidth();
1038            final int maxX = Math.max(0, right - width);
1039            final int scrollX = mScrollX;
1040            dx = Math.max(0, Math.min(scrollX + dx, maxX)) - scrollX;
1041
1042            mScroller.startScroll(scrollX, mScrollY, dx, 0);
1043            invalidate();
1044        } else {
1045            if (!mScroller.isFinished()) {
1046                mScroller.abortAnimation();
1047            }
1048            scrollBy(dx, dy);
1049        }
1050        mLastScroll = AnimationUtils.currentAnimationTimeMillis();
1051    }
1052
1053    /**
1054     * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
1055     *
1056     * @param x the position where to scroll on the X axis
1057     * @param y the position where to scroll on the Y axis
1058     */
1059    public final void smoothScrollTo(int x, int y) {
1060        smoothScrollBy(x - mScrollX, y - mScrollY);
1061    }
1062
1063    /**
1064     * <p>The scroll range of a scroll view is the overall width of all of its
1065     * children.</p>
1066     */
1067    @Override
1068    protected int computeHorizontalScrollRange() {
1069        final int count = getChildCount();
1070        final int contentWidth = getWidth() - mPaddingLeft - mPaddingRight;
1071        if (count == 0) {
1072            return contentWidth;
1073        }
1074
1075        int scrollRange = getChildAt(0).getRight();
1076        final int scrollX = mScrollX;
1077        final int overscrollRight = Math.max(0, scrollRange - contentWidth);
1078        if (scrollX < 0) {
1079            scrollRange -= scrollX;
1080        } else if (scrollX > overscrollRight) {
1081            scrollRange += scrollX - overscrollRight;
1082        }
1083
1084        return scrollRange;
1085    }
1086
1087    @Override
1088    protected int computeHorizontalScrollOffset() {
1089        return Math.max(0, super.computeHorizontalScrollOffset());
1090    }
1091
1092    @Override
1093    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
1094        ViewGroup.LayoutParams lp = child.getLayoutParams();
1095
1096        int childWidthMeasureSpec;
1097        int childHeightMeasureSpec;
1098
1099        childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop
1100                + mPaddingBottom, lp.height);
1101
1102        childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1103
1104        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1105    }
1106
1107    @Override
1108    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
1109            int parentHeightMeasureSpec, int heightUsed) {
1110        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
1111
1112        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
1113                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
1114                        + heightUsed, lp.height);
1115        final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
1116                lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);
1117
1118        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1119    }
1120
1121    @Override
1122    public void computeScroll() {
1123        if (mScroller.computeScrollOffset()) {
1124            // This is called at drawing time by ViewGroup.  We don't want to
1125            // re-show the scrollbars at this point, which scrollTo will do,
1126            // so we replicate most of scrollTo here.
1127            //
1128            //         It's a little odd to call onScrollChanged from inside the drawing.
1129            //
1130            //         It is, except when you remember that computeScroll() is used to
1131            //         animate scrolling. So unless we want to defer the onScrollChanged()
1132            //         until the end of the animated scrolling, we don't really have a
1133            //         choice here.
1134            //
1135            //         I agree.  The alternative, which I think would be worse, is to post
1136            //         something and tell the subclasses later.  This is bad because there
1137            //         will be a window where mScrollX/Y is different from what the app
1138            //         thinks it is.
1139            //
1140            int oldX = mScrollX;
1141            int oldY = mScrollY;
1142            int x = mScroller.getCurrX();
1143            int y = mScroller.getCurrY();
1144
1145            if (oldX != x || oldY != y) {
1146                overScrollBy(x - oldX, y - oldY, oldX, oldY, getScrollRange(), 0,
1147                        mOverflingDistance, 0, false);
1148                onScrollChanged(mScrollX, mScrollY, oldX, oldY);
1149
1150                final int range = getScrollRange();
1151                final int overscrollMode = getOverScrollMode();
1152                if (overscrollMode == OVER_SCROLL_ALWAYS ||
1153                        (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0)) {
1154                    if (x < 0 && oldX >= 0) {
1155                        mEdgeGlowLeft.onAbsorb((int) mScroller.getCurrVelocity());
1156                    } else if (x > range && oldX <= range) {
1157                        mEdgeGlowRight.onAbsorb((int) mScroller.getCurrVelocity());
1158                    }
1159                }
1160            }
1161            awakenScrollBars();
1162
1163            // Keep on drawing until the animation has finished.
1164            postInvalidate();
1165        }
1166    }
1167
1168    /**
1169     * Scrolls the view to the given child.
1170     *
1171     * @param child the View to scroll to
1172     */
1173    private void scrollToChild(View child) {
1174        child.getDrawingRect(mTempRect);
1175
1176        /* Offset from child's local coordinates to ScrollView coordinates */
1177        offsetDescendantRectToMyCoords(child, mTempRect);
1178
1179        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1180
1181        if (scrollDelta != 0) {
1182            scrollBy(scrollDelta, 0);
1183        }
1184    }
1185
1186    /**
1187     * If rect is off screen, scroll just enough to get it (or at least the
1188     * first screen size chunk of it) on screen.
1189     *
1190     * @param rect      The rectangle.
1191     * @param immediate True to scroll immediately without animation
1192     * @return true if scrolling was performed
1193     */
1194    private boolean scrollToChildRect(Rect rect, boolean immediate) {
1195        final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
1196        final boolean scroll = delta != 0;
1197        if (scroll) {
1198            if (immediate) {
1199                scrollBy(delta, 0);
1200            } else {
1201                smoothScrollBy(delta, 0);
1202            }
1203        }
1204        return scroll;
1205    }
1206
1207    /**
1208     * Compute the amount to scroll in the X direction in order to get
1209     * a rectangle completely on the screen (or, if taller than the screen,
1210     * at least the first screen size chunk of it).
1211     *
1212     * @param rect The rect.
1213     * @return The scroll delta.
1214     */
1215    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
1216        if (getChildCount() == 0) return 0;
1217
1218        int width = getWidth();
1219        int screenLeft = getScrollX();
1220        int screenRight = screenLeft + width;
1221
1222        int fadingEdge = getHorizontalFadingEdgeLength();
1223
1224        // leave room for left fading edge as long as rect isn't at very left
1225        if (rect.left > 0) {
1226            screenLeft += fadingEdge;
1227        }
1228
1229        // leave room for right fading edge as long as rect isn't at very right
1230        if (rect.right < getChildAt(0).getWidth()) {
1231            screenRight -= fadingEdge;
1232        }
1233
1234        int scrollXDelta = 0;
1235
1236        if (rect.right > screenRight && rect.left > screenLeft) {
1237            // need to move right to get it in view: move right just enough so
1238            // that the entire rectangle is in view (or at least the first
1239            // screen size chunk).
1240
1241            if (rect.width() > width) {
1242                // just enough to get screen size chunk on
1243                scrollXDelta += (rect.left - screenLeft);
1244            } else {
1245                // get entire rect at right of screen
1246                scrollXDelta += (rect.right - screenRight);
1247            }
1248
1249            // make sure we aren't scrolling beyond the end of our content
1250            int right = getChildAt(0).getRight();
1251            int distanceToRight = right - screenRight;
1252            scrollXDelta = Math.min(scrollXDelta, distanceToRight);
1253
1254        } else if (rect.left < screenLeft && rect.right < screenRight) {
1255            // need to move right to get it in view: move right just enough so that
1256            // entire rectangle is in view (or at least the first screen
1257            // size chunk of it).
1258
1259            if (rect.width() > width) {
1260                // screen size chunk
1261                scrollXDelta -= (screenRight - rect.right);
1262            } else {
1263                // entire rect at left
1264                scrollXDelta -= (screenLeft - rect.left);
1265            }
1266
1267            // make sure we aren't scrolling any further than the left our content
1268            scrollXDelta = Math.max(scrollXDelta, -getScrollX());
1269        }
1270        return scrollXDelta;
1271    }
1272
1273    @Override
1274    public void requestChildFocus(View child, View focused) {
1275        if (!mIsLayoutDirty) {
1276            scrollToChild(focused);
1277        } else {
1278            // The child may not be laid out yet, we can't compute the scroll yet
1279            mChildToScrollTo = focused;
1280        }
1281        super.requestChildFocus(child, focused);
1282    }
1283
1284
1285    /**
1286     * When looking for focus in children of a scroll view, need to be a little
1287     * more careful not to give focus to something that is scrolled off screen.
1288     *
1289     * This is more expensive than the default {@link android.view.ViewGroup}
1290     * implementation, otherwise this behavior might have been made the default.
1291     */
1292    @Override
1293    protected boolean onRequestFocusInDescendants(int direction,
1294            Rect previouslyFocusedRect) {
1295
1296        // convert from forward / backward notation to up / down / left / right
1297        // (ugh).
1298        if (direction == View.FOCUS_FORWARD) {
1299            direction = View.FOCUS_RIGHT;
1300        } else if (direction == View.FOCUS_BACKWARD) {
1301            direction = View.FOCUS_LEFT;
1302        }
1303
1304        final View nextFocus = previouslyFocusedRect == null ?
1305                FocusFinder.getInstance().findNextFocus(this, null, direction) :
1306                FocusFinder.getInstance().findNextFocusFromRect(this,
1307                        previouslyFocusedRect, direction);
1308
1309        if (nextFocus == null) {
1310            return false;
1311        }
1312
1313        if (isOffScreen(nextFocus)) {
1314            return false;
1315        }
1316
1317        return nextFocus.requestFocus(direction, previouslyFocusedRect);
1318    }
1319
1320    @Override
1321    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1322            boolean immediate) {
1323        // offset into coordinate space of this scroll view
1324        rectangle.offset(child.getLeft() - child.getScrollX(),
1325                child.getTop() - child.getScrollY());
1326
1327        return scrollToChildRect(rectangle, immediate);
1328    }
1329
1330    @Override
1331    public void requestLayout() {
1332        mIsLayoutDirty = true;
1333        super.requestLayout();
1334    }
1335
1336    @Override
1337    protected void onLayout(boolean changed, int l, int t, int r, int b) {
1338        super.onLayout(changed, l, t, r, b);
1339        mIsLayoutDirty = false;
1340        // Give a child focus if it needs it
1341        if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1342                scrollToChild(mChildToScrollTo);
1343        }
1344        mChildToScrollTo = null;
1345
1346        // Calling this with the present values causes it to re-clam them
1347        scrollTo(mScrollX, mScrollY);
1348    }
1349
1350    @Override
1351    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1352        super.onSizeChanged(w, h, oldw, oldh);
1353
1354        View currentFocused = findFocus();
1355        if (null == currentFocused || this == currentFocused)
1356            return;
1357
1358        final int maxJump = mRight - mLeft;
1359
1360        if (isWithinDeltaOfScreen(currentFocused, maxJump)) {
1361            currentFocused.getDrawingRect(mTempRect);
1362            offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1363            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1364            doScrollX(scrollDelta);
1365        }
1366    }
1367
1368    /**
1369     * Return true if child is an descendant of parent, (or equal to the parent).
1370     */
1371    private boolean isViewDescendantOf(View child, View parent) {
1372        if (child == parent) {
1373            return true;
1374        }
1375
1376        final ViewParent theParent = child.getParent();
1377        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1378    }
1379
1380    /**
1381     * Fling the scroll view
1382     *
1383     * @param velocityX The initial velocity in the X direction. Positive
1384     *                  numbers mean that the finger/curor is moving down the screen,
1385     *                  which means we want to scroll towards the left.
1386     */
1387    public void fling(int velocityX) {
1388        if (getChildCount() > 0) {
1389            int width = getWidth() - mPaddingRight - mPaddingLeft;
1390            int right = getChildAt(0).getWidth();
1391
1392            mScroller.fling(mScrollX, mScrollY, velocityX, 0, 0,
1393                    Math.max(0, right - width), 0, 0, width/2, 0);
1394
1395            final boolean movingRight = velocityX > 0;
1396
1397            View currentFocused = findFocus();
1398            View newFocused = findFocusableViewInMyBounds(movingRight,
1399                    mScroller.getFinalX(), currentFocused);
1400
1401            if (newFocused == null) {
1402                newFocused = this;
1403            }
1404
1405            if (newFocused != currentFocused) {
1406                newFocused.requestFocus(movingRight ? View.FOCUS_RIGHT : View.FOCUS_LEFT);
1407            }
1408
1409            invalidate();
1410        }
1411    }
1412
1413    /**
1414     * {@inheritDoc}
1415     *
1416     * <p>This version also clamps the scrolling to the bounds of our child.
1417     */
1418    @Override
1419    public void scrollTo(int x, int y) {
1420        // we rely on the fact the View.scrollBy calls scrollTo.
1421        if (getChildCount() > 0) {
1422            View child = getChildAt(0);
1423            x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1424            y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1425            if (x != mScrollX || y != mScrollY) {
1426                super.scrollTo(x, y);
1427            }
1428        }
1429    }
1430
1431    @Override
1432    public void setOverScrollMode(int mode) {
1433        if (mode != OVER_SCROLL_NEVER) {
1434            if (mEdgeGlowLeft == null) {
1435                Context context = getContext();
1436                final Resources res = context.getResources();
1437                final Drawable edge = res.getDrawable(R.drawable.overscroll_edge);
1438                final Drawable glow = res.getDrawable(R.drawable.overscroll_glow);
1439                mEdgeGlowLeft = new EdgeGlow(context, edge, glow);
1440                mEdgeGlowRight = new EdgeGlow(context, edge, glow);
1441            }
1442        } else {
1443            mEdgeGlowLeft = null;
1444            mEdgeGlowRight = null;
1445        }
1446        super.setOverScrollMode(mode);
1447    }
1448
1449    @Override
1450    public void draw(Canvas canvas) {
1451        super.draw(canvas);
1452        if (mEdgeGlowLeft != null) {
1453            final int scrollX = mScrollX;
1454            if (!mEdgeGlowLeft.isFinished()) {
1455                final int restoreCount = canvas.save();
1456                final int height = getHeight() - mPaddingTop - mPaddingBottom;
1457
1458                canvas.rotate(270);
1459                canvas.translate(-height + mPaddingTop, Math.min(0, scrollX));
1460                mEdgeGlowLeft.setSize(height, getWidth());
1461                if (mEdgeGlowLeft.draw(canvas)) {
1462                    invalidate();
1463                }
1464                canvas.restoreToCount(restoreCount);
1465            }
1466            if (!mEdgeGlowRight.isFinished()) {
1467                final int restoreCount = canvas.save();
1468                final int width = getWidth();
1469                final int height = getHeight() - mPaddingTop - mPaddingBottom;
1470
1471                canvas.rotate(90);
1472                canvas.translate(-mPaddingTop,
1473                        -(Math.max(getScrollRange(), scrollX) + width));
1474                mEdgeGlowRight.setSize(height, width);
1475                if (mEdgeGlowRight.draw(canvas)) {
1476                    invalidate();
1477                }
1478                canvas.restoreToCount(restoreCount);
1479            }
1480        }
1481    }
1482
1483    private int clamp(int n, int my, int child) {
1484        if (my >= child || n < 0) {
1485            return 0;
1486        }
1487        if ((my + n) > child) {
1488            return child - my;
1489        }
1490        return n;
1491    }
1492}
1493