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