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