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