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