HorizontalScrollView.java revision fb1e80a247221ee7e8f5c5deba04812021d9d07e
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        if (super.performAccessibilityAction(action, arguments)) {
743            return true;
744        }
745        switch (action) {
746            case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
747                if (!isEnabled()) {
748                    return false;
749                }
750                final int viewportWidth = getWidth() - mPaddingLeft - mPaddingRight;
751                final int targetScrollX = Math.min(mScrollX + viewportWidth, getScrollRange());
752                if (targetScrollX != mScrollX) {
753                    smoothScrollTo(targetScrollX, 0);
754                    return true;
755                }
756            } return false;
757            case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
758                if (!isEnabled()) {
759                    return false;
760                }
761                final int viewportWidth = getWidth() - mPaddingLeft - mPaddingRight;
762                final int targetScrollX = Math.max(0, mScrollX - viewportWidth);
763                if (targetScrollX != mScrollX) {
764                    smoothScrollTo(targetScrollX, 0);
765                    return true;
766                }
767            } return false;
768        }
769        return false;
770    }
771
772    @Override
773    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
774        super.onInitializeAccessibilityNodeInfo(info);
775        info.setClassName(HorizontalScrollView.class.getName());
776        final int scrollRange = getScrollRange();
777        if (scrollRange > 0) {
778            info.setScrollable(true);
779            if (isEnabled() && mScrollX > 0) {
780                info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
781            }
782            if (isEnabled() && mScrollX < scrollRange) {
783                info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
784            }
785        }
786    }
787
788    @Override
789    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
790        super.onInitializeAccessibilityEvent(event);
791        event.setClassName(HorizontalScrollView.class.getName());
792        event.setScrollable(getScrollRange() > 0);
793        event.setScrollX(mScrollX);
794        event.setScrollY(mScrollY);
795        event.setMaxScrollX(getScrollRange());
796        event.setMaxScrollY(mScrollY);
797    }
798
799    private int getScrollRange() {
800        int scrollRange = 0;
801        if (getChildCount() > 0) {
802            View child = getChildAt(0);
803            scrollRange = Math.max(0,
804                    child.getWidth() - (getWidth() - mPaddingLeft - mPaddingRight));
805        }
806        return scrollRange;
807    }
808
809    /**
810     * <p>
811     * Finds the next focusable component that fits in this View's bounds
812     * (excluding fading edges) pretending that this View's left is located at
813     * the parameter left.
814     * </p>
815     *
816     * @param leftFocus          look for a candidate is the one at the left of the bounds
817     *                           if leftFocus is true, or at the right of the bounds if leftFocus
818     *                           is false
819     * @param left               the left offset of the bounds in which a focusable must be
820     *                           found (the fading edge is assumed to start at this position)
821     * @param preferredFocusable the View that has highest priority and will be
822     *                           returned if it is within my bounds (null is valid)
823     * @return the next focusable component in the bounds or null if none can be found
824     */
825    private View findFocusableViewInMyBounds(final boolean leftFocus,
826            final int left, View preferredFocusable) {
827        /*
828         * The fading edge's transparent side should be considered for focus
829         * since it's mostly visible, so we divide the actual fading edge length
830         * by 2.
831         */
832        final int fadingEdgeLength = getHorizontalFadingEdgeLength() / 2;
833        final int leftWithoutFadingEdge = left + fadingEdgeLength;
834        final int rightWithoutFadingEdge = left + getWidth() - fadingEdgeLength;
835
836        if ((preferredFocusable != null)
837                && (preferredFocusable.getLeft() < rightWithoutFadingEdge)
838                && (preferredFocusable.getRight() > leftWithoutFadingEdge)) {
839            return preferredFocusable;
840        }
841
842        return findFocusableViewInBounds(leftFocus, leftWithoutFadingEdge,
843                rightWithoutFadingEdge);
844    }
845
846    /**
847     * <p>
848     * Finds the next focusable component that fits in the specified bounds.
849     * </p>
850     *
851     * @param leftFocus look for a candidate is the one at the left of the bounds
852     *                  if leftFocus is true, or at the right of the bounds if
853     *                  leftFocus is false
854     * @param left      the left offset of the bounds in which a focusable must be
855     *                  found
856     * @param right     the right offset of the bounds in which a focusable must
857     *                  be found
858     * @return the next focusable component in the bounds or null if none can
859     *         be found
860     */
861    private View findFocusableViewInBounds(boolean leftFocus, int left, int right) {
862
863        List<View> focusables = getFocusables(View.FOCUS_FORWARD);
864        View focusCandidate = null;
865
866        /*
867         * A fully contained focusable is one where its left is below the bound's
868         * left, and its right is above the bound's right. A partially
869         * contained focusable is one where some part of it is within the
870         * bounds, but it also has some part that is not within bounds.  A fully contained
871         * focusable is preferred to a partially contained focusable.
872         */
873        boolean foundFullyContainedFocusable = false;
874
875        int count = focusables.size();
876        for (int i = 0; i < count; i++) {
877            View view = focusables.get(i);
878            int viewLeft = view.getLeft();
879            int viewRight = view.getRight();
880
881            if (left < viewRight && viewLeft < right) {
882                /*
883                 * the focusable is in the target area, it is a candidate for
884                 * focusing
885                 */
886
887                final boolean viewIsFullyContained = (left < viewLeft) &&
888                        (viewRight < right);
889
890                if (focusCandidate == null) {
891                    /* No candidate, take this one */
892                    focusCandidate = view;
893                    foundFullyContainedFocusable = viewIsFullyContained;
894                } else {
895                    final boolean viewIsCloserToBoundary =
896                            (leftFocus && viewLeft < focusCandidate.getLeft()) ||
897                                    (!leftFocus && viewRight > focusCandidate.getRight());
898
899                    if (foundFullyContainedFocusable) {
900                        if (viewIsFullyContained && viewIsCloserToBoundary) {
901                            /*
902                             * We're dealing with only fully contained views, so
903                             * it has to be closer to the boundary to beat our
904                             * candidate
905                             */
906                            focusCandidate = view;
907                        }
908                    } else {
909                        if (viewIsFullyContained) {
910                            /* Any fully contained view beats a partially contained view */
911                            focusCandidate = view;
912                            foundFullyContainedFocusable = true;
913                        } else if (viewIsCloserToBoundary) {
914                            /*
915                             * Partially contained view beats another partially
916                             * contained view if it's closer
917                             */
918                            focusCandidate = view;
919                        }
920                    }
921                }
922            }
923        }
924
925        return focusCandidate;
926    }
927
928    /**
929     * <p>Handles scrolling in response to a "page up/down" shortcut press. This
930     * method will scroll the view by one page left or right and give the focus
931     * to the leftmost/rightmost component in the new visible area. If no
932     * component is a good candidate for focus, this scrollview reclaims the
933     * focus.</p>
934     *
935     * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT}
936     *                  to go one page left or {@link android.view.View#FOCUS_RIGHT}
937     *                  to go one page right
938     * @return true if the key event is consumed by this method, false otherwise
939     */
940    public boolean pageScroll(int direction) {
941        boolean right = direction == View.FOCUS_RIGHT;
942        int width = getWidth();
943
944        if (right) {
945            mTempRect.left = getScrollX() + width;
946            int count = getChildCount();
947            if (count > 0) {
948                View view = getChildAt(0);
949                if (mTempRect.left + width > view.getRight()) {
950                    mTempRect.left = view.getRight() - width;
951                }
952            }
953        } else {
954            mTempRect.left = getScrollX() - width;
955            if (mTempRect.left < 0) {
956                mTempRect.left = 0;
957            }
958        }
959        mTempRect.right = mTempRect.left + width;
960
961        return scrollAndFocus(direction, mTempRect.left, mTempRect.right);
962    }
963
964    /**
965     * <p>Handles scrolling in response to a "home/end" shortcut press. This
966     * method will scroll the view to the left or right and give the focus
967     * to the leftmost/rightmost component in the new visible area. If no
968     * component is a good candidate for focus, this scrollview reclaims the
969     * focus.</p>
970     *
971     * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT}
972     *                  to go the left of the view or {@link android.view.View#FOCUS_RIGHT}
973     *                  to go the right
974     * @return true if the key event is consumed by this method, false otherwise
975     */
976    public boolean fullScroll(int direction) {
977        boolean right = direction == View.FOCUS_RIGHT;
978        int width = getWidth();
979
980        mTempRect.left = 0;
981        mTempRect.right = width;
982
983        if (right) {
984            int count = getChildCount();
985            if (count > 0) {
986                View view = getChildAt(0);
987                mTempRect.right = view.getRight();
988                mTempRect.left = mTempRect.right - width;
989            }
990        }
991
992        return scrollAndFocus(direction, mTempRect.left, mTempRect.right);
993    }
994
995    /**
996     * <p>Scrolls the view to make the area defined by <code>left</code> and
997     * <code>right</code> visible. This method attempts to give the focus
998     * to a component visible in this area. If no component can be focused in
999     * the new visible area, the focus is reclaimed by this scrollview.</p>
1000     *
1001     * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT}
1002     *                  to go left {@link android.view.View#FOCUS_RIGHT} to right
1003     * @param left     the left offset of the new area to be made visible
1004     * @param right    the right offset of the new area to be made visible
1005     * @return true if the key event is consumed by this method, false otherwise
1006     */
1007    private boolean scrollAndFocus(int direction, int left, int right) {
1008        boolean handled = true;
1009
1010        int width = getWidth();
1011        int containerLeft = getScrollX();
1012        int containerRight = containerLeft + width;
1013        boolean goLeft = direction == View.FOCUS_LEFT;
1014
1015        View newFocused = findFocusableViewInBounds(goLeft, left, right);
1016        if (newFocused == null) {
1017            newFocused = this;
1018        }
1019
1020        if (left >= containerLeft && right <= containerRight) {
1021            handled = false;
1022        } else {
1023            int delta = goLeft ? (left - containerLeft) : (right - containerRight);
1024            doScrollX(delta);
1025        }
1026
1027        if (newFocused != findFocus()) newFocused.requestFocus(direction);
1028
1029        return handled;
1030    }
1031
1032    /**
1033     * Handle scrolling in response to a left or right arrow click.
1034     *
1035     * @param direction The direction corresponding to the arrow key that was
1036     *                  pressed
1037     * @return True if we consumed the event, false otherwise
1038     */
1039    public boolean arrowScroll(int direction) {
1040
1041        View currentFocused = findFocus();
1042        if (currentFocused == this) currentFocused = null;
1043
1044        View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
1045
1046        final int maxJump = getMaxScrollAmount();
1047
1048        if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump)) {
1049            nextFocused.getDrawingRect(mTempRect);
1050            offsetDescendantRectToMyCoords(nextFocused, mTempRect);
1051            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1052            doScrollX(scrollDelta);
1053            nextFocused.requestFocus(direction);
1054        } else {
1055            // no new focus
1056            int scrollDelta = maxJump;
1057
1058            if (direction == View.FOCUS_LEFT && getScrollX() < scrollDelta) {
1059                scrollDelta = getScrollX();
1060            } else if (direction == View.FOCUS_RIGHT && getChildCount() > 0) {
1061
1062                int daRight = getChildAt(0).getRight();
1063
1064                int screenRight = getScrollX() + getWidth();
1065
1066                if (daRight - screenRight < maxJump) {
1067                    scrollDelta = daRight - screenRight;
1068                }
1069            }
1070            if (scrollDelta == 0) {
1071                return false;
1072            }
1073            doScrollX(direction == View.FOCUS_RIGHT ? scrollDelta : -scrollDelta);
1074        }
1075
1076        if (currentFocused != null && currentFocused.isFocused()
1077                && isOffScreen(currentFocused)) {
1078            // previously focused item still has focus and is off screen, give
1079            // it up (take it back to ourselves)
1080            // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
1081            // sure to
1082            // get it)
1083            final int descendantFocusability = getDescendantFocusability();  // save
1084            setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
1085            requestFocus();
1086            setDescendantFocusability(descendantFocusability);  // restore
1087        }
1088        return true;
1089    }
1090
1091    /**
1092     * @return whether the descendant of this scroll view is scrolled off
1093     *  screen.
1094     */
1095    private boolean isOffScreen(View descendant) {
1096        return !isWithinDeltaOfScreen(descendant, 0);
1097    }
1098
1099    /**
1100     * @return whether the descendant of this scroll view is within delta
1101     *  pixels of being on the screen.
1102     */
1103    private boolean isWithinDeltaOfScreen(View descendant, int delta) {
1104        descendant.getDrawingRect(mTempRect);
1105        offsetDescendantRectToMyCoords(descendant, mTempRect);
1106
1107        return (mTempRect.right + delta) >= getScrollX()
1108                && (mTempRect.left - delta) <= (getScrollX() + getWidth());
1109    }
1110
1111    /**
1112     * Smooth scroll by a X delta
1113     *
1114     * @param delta the number of pixels to scroll by on the X axis
1115     */
1116    private void doScrollX(int delta) {
1117        if (delta != 0) {
1118            if (mSmoothScrollingEnabled) {
1119                smoothScrollBy(delta, 0);
1120            } else {
1121                scrollBy(delta, 0);
1122            }
1123        }
1124    }
1125
1126    /**
1127     * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
1128     *
1129     * @param dx the number of pixels to scroll by on the X axis
1130     * @param dy the number of pixels to scroll by on the Y axis
1131     */
1132    public final void smoothScrollBy(int dx, int dy) {
1133        if (getChildCount() == 0) {
1134            // Nothing to do.
1135            return;
1136        }
1137        long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
1138        if (duration > ANIMATED_SCROLL_GAP) {
1139            final int width = getWidth() - mPaddingRight - mPaddingLeft;
1140            final int right = getChildAt(0).getWidth();
1141            final int maxX = Math.max(0, right - width);
1142            final int scrollX = mScrollX;
1143            dx = Math.max(0, Math.min(scrollX + dx, maxX)) - scrollX;
1144
1145            mScroller.startScroll(scrollX, mScrollY, dx, 0);
1146            postInvalidateOnAnimation();
1147        } else {
1148            if (!mScroller.isFinished()) {
1149                mScroller.abortAnimation();
1150            }
1151            scrollBy(dx, dy);
1152        }
1153        mLastScroll = AnimationUtils.currentAnimationTimeMillis();
1154    }
1155
1156    /**
1157     * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
1158     *
1159     * @param x the position where to scroll on the X axis
1160     * @param y the position where to scroll on the Y axis
1161     */
1162    public final void smoothScrollTo(int x, int y) {
1163        smoothScrollBy(x - mScrollX, y - mScrollY);
1164    }
1165
1166    /**
1167     * <p>The scroll range of a scroll view is the overall width of all of its
1168     * children.</p>
1169     */
1170    @Override
1171    protected int computeHorizontalScrollRange() {
1172        final int count = getChildCount();
1173        final int contentWidth = getWidth() - mPaddingLeft - mPaddingRight;
1174        if (count == 0) {
1175            return contentWidth;
1176        }
1177
1178        int scrollRange = getChildAt(0).getRight();
1179        final int scrollX = mScrollX;
1180        final int overscrollRight = Math.max(0, scrollRange - contentWidth);
1181        if (scrollX < 0) {
1182            scrollRange -= scrollX;
1183        } else if (scrollX > overscrollRight) {
1184            scrollRange += scrollX - overscrollRight;
1185        }
1186
1187        return scrollRange;
1188    }
1189
1190    @Override
1191    protected int computeHorizontalScrollOffset() {
1192        return Math.max(0, super.computeHorizontalScrollOffset());
1193    }
1194
1195    @Override
1196    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
1197        ViewGroup.LayoutParams lp = child.getLayoutParams();
1198
1199        int childWidthMeasureSpec;
1200        int childHeightMeasureSpec;
1201
1202        childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop
1203                + mPaddingBottom, lp.height);
1204
1205        childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1206
1207        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1208    }
1209
1210    @Override
1211    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
1212            int parentHeightMeasureSpec, int heightUsed) {
1213        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
1214
1215        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
1216                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
1217                        + heightUsed, lp.height);
1218        final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
1219                lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);
1220
1221        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1222    }
1223
1224    @Override
1225    public void computeScroll() {
1226        if (mScroller.computeScrollOffset()) {
1227            // This is called at drawing time by ViewGroup.  We don't want to
1228            // re-show the scrollbars at this point, which scrollTo will do,
1229            // so we replicate most of scrollTo here.
1230            //
1231            //         It's a little odd to call onScrollChanged from inside the drawing.
1232            //
1233            //         It is, except when you remember that computeScroll() is used to
1234            //         animate scrolling. So unless we want to defer the onScrollChanged()
1235            //         until the end of the animated scrolling, we don't really have a
1236            //         choice here.
1237            //
1238            //         I agree.  The alternative, which I think would be worse, is to post
1239            //         something and tell the subclasses later.  This is bad because there
1240            //         will be a window where mScrollX/Y is different from what the app
1241            //         thinks it is.
1242            //
1243            int oldX = mScrollX;
1244            int oldY = mScrollY;
1245            int x = mScroller.getCurrX();
1246            int y = mScroller.getCurrY();
1247
1248            if (oldX != x || oldY != y) {
1249                final int range = getScrollRange();
1250                final int overscrollMode = getOverScrollMode();
1251                final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS ||
1252                        (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0);
1253
1254                overScrollBy(x - oldX, y - oldY, oldX, oldY, range, 0,
1255                        mOverflingDistance, 0, false);
1256                onScrollChanged(mScrollX, mScrollY, oldX, oldY);
1257
1258                if (canOverscroll) {
1259                    if (x < 0 && oldX >= 0) {
1260                        mEdgeGlowLeft.onAbsorb((int) mScroller.getCurrVelocity());
1261                    } else if (x > range && oldX <= range) {
1262                        mEdgeGlowRight.onAbsorb((int) mScroller.getCurrVelocity());
1263                    }
1264                }
1265            }
1266
1267            if (!awakenScrollBars()) {
1268                postInvalidateOnAnimation();
1269            }
1270        }
1271    }
1272
1273    /**
1274     * Scrolls the view to the given child.
1275     *
1276     * @param child the View to scroll to
1277     */
1278    private void scrollToChild(View child) {
1279        child.getDrawingRect(mTempRect);
1280
1281        /* Offset from child's local coordinates to ScrollView coordinates */
1282        offsetDescendantRectToMyCoords(child, mTempRect);
1283
1284        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1285
1286        if (scrollDelta != 0) {
1287            scrollBy(scrollDelta, 0);
1288        }
1289    }
1290
1291    /**
1292     * If rect is off screen, scroll just enough to get it (or at least the
1293     * first screen size chunk of it) on screen.
1294     *
1295     * @param rect      The rectangle.
1296     * @param immediate True to scroll immediately without animation
1297     * @return true if scrolling was performed
1298     */
1299    private boolean scrollToChildRect(Rect rect, boolean immediate) {
1300        final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
1301        final boolean scroll = delta != 0;
1302        if (scroll) {
1303            if (immediate) {
1304                scrollBy(delta, 0);
1305            } else {
1306                smoothScrollBy(delta, 0);
1307            }
1308        }
1309        return scroll;
1310    }
1311
1312    /**
1313     * Compute the amount to scroll in the X direction in order to get
1314     * a rectangle completely on the screen (or, if taller than the screen,
1315     * at least the first screen size chunk of it).
1316     *
1317     * @param rect The rect.
1318     * @return The scroll delta.
1319     */
1320    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
1321        if (getChildCount() == 0) return 0;
1322
1323        int width = getWidth();
1324        int screenLeft = getScrollX();
1325        int screenRight = screenLeft + width;
1326
1327        int fadingEdge = getHorizontalFadingEdgeLength();
1328
1329        // leave room for left fading edge as long as rect isn't at very left
1330        if (rect.left > 0) {
1331            screenLeft += fadingEdge;
1332        }
1333
1334        // leave room for right fading edge as long as rect isn't at very right
1335        if (rect.right < getChildAt(0).getWidth()) {
1336            screenRight -= fadingEdge;
1337        }
1338
1339        int scrollXDelta = 0;
1340
1341        if (rect.right > screenRight && rect.left > screenLeft) {
1342            // need to move right to get it in view: move right just enough so
1343            // that the entire rectangle is in view (or at least the first
1344            // screen size chunk).
1345
1346            if (rect.width() > width) {
1347                // just enough to get screen size chunk on
1348                scrollXDelta += (rect.left - screenLeft);
1349            } else {
1350                // get entire rect at right of screen
1351                scrollXDelta += (rect.right - screenRight);
1352            }
1353
1354            // make sure we aren't scrolling beyond the end of our content
1355            int right = getChildAt(0).getRight();
1356            int distanceToRight = right - screenRight;
1357            scrollXDelta = Math.min(scrollXDelta, distanceToRight);
1358
1359        } else if (rect.left < screenLeft && rect.right < screenRight) {
1360            // need to move right to get it in view: move right just enough so that
1361            // entire rectangle is in view (or at least the first screen
1362            // size chunk of it).
1363
1364            if (rect.width() > width) {
1365                // screen size chunk
1366                scrollXDelta -= (screenRight - rect.right);
1367            } else {
1368                // entire rect at left
1369                scrollXDelta -= (screenLeft - rect.left);
1370            }
1371
1372            // make sure we aren't scrolling any further than the left our content
1373            scrollXDelta = Math.max(scrollXDelta, -getScrollX());
1374        }
1375        return scrollXDelta;
1376    }
1377
1378    @Override
1379    public void requestChildFocus(View child, View focused) {
1380        if (!mIsLayoutDirty) {
1381            scrollToChild(focused);
1382        } else {
1383            // The child may not be laid out yet, we can't compute the scroll yet
1384            mChildToScrollTo = focused;
1385        }
1386        super.requestChildFocus(child, focused);
1387    }
1388
1389
1390    /**
1391     * When looking for focus in children of a scroll view, need to be a little
1392     * more careful not to give focus to something that is scrolled off screen.
1393     *
1394     * This is more expensive than the default {@link android.view.ViewGroup}
1395     * implementation, otherwise this behavior might have been made the default.
1396     */
1397    @Override
1398    protected boolean onRequestFocusInDescendants(int direction,
1399            Rect previouslyFocusedRect) {
1400
1401        // convert from forward / backward notation to up / down / left / right
1402        // (ugh).
1403        if (direction == View.FOCUS_FORWARD) {
1404            direction = View.FOCUS_RIGHT;
1405        } else if (direction == View.FOCUS_BACKWARD) {
1406            direction = View.FOCUS_LEFT;
1407        }
1408
1409        final View nextFocus = previouslyFocusedRect == null ?
1410                FocusFinder.getInstance().findNextFocus(this, null, direction) :
1411                FocusFinder.getInstance().findNextFocusFromRect(this,
1412                        previouslyFocusedRect, direction);
1413
1414        if (nextFocus == null) {
1415            return false;
1416        }
1417
1418        if (isOffScreen(nextFocus)) {
1419            return false;
1420        }
1421
1422        return nextFocus.requestFocus(direction, previouslyFocusedRect);
1423    }
1424
1425    @Override
1426    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1427            boolean immediate) {
1428        // offset into coordinate space of this scroll view
1429        rectangle.offset(child.getLeft() - child.getScrollX(),
1430                child.getTop() - child.getScrollY());
1431
1432        return scrollToChildRect(rectangle, immediate);
1433    }
1434
1435    @Override
1436    public void requestLayout() {
1437        mIsLayoutDirty = true;
1438        super.requestLayout();
1439    }
1440
1441    @Override
1442    protected void onLayout(boolean changed, int l, int t, int r, int b) {
1443        super.onLayout(changed, l, t, r, b);
1444        mIsLayoutDirty = false;
1445        // Give a child focus if it needs it
1446        if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1447                scrollToChild(mChildToScrollTo);
1448        }
1449        mChildToScrollTo = null;
1450
1451        // Calling this with the present values causes it to re-claim them
1452        scrollTo(mScrollX, mScrollY);
1453    }
1454
1455    @Override
1456    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1457        super.onSizeChanged(w, h, oldw, oldh);
1458
1459        View currentFocused = findFocus();
1460        if (null == currentFocused || this == currentFocused)
1461            return;
1462
1463        final int maxJump = mRight - mLeft;
1464
1465        if (isWithinDeltaOfScreen(currentFocused, maxJump)) {
1466            currentFocused.getDrawingRect(mTempRect);
1467            offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1468            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1469            doScrollX(scrollDelta);
1470        }
1471    }
1472
1473    /**
1474     * Return true if child is a descendant of parent, (or equal to the parent).
1475     */
1476    private static boolean isViewDescendantOf(View child, View parent) {
1477        if (child == parent) {
1478            return true;
1479        }
1480
1481        final ViewParent theParent = child.getParent();
1482        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1483    }
1484
1485    /**
1486     * Fling the scroll view
1487     *
1488     * @param velocityX The initial velocity in the X direction. Positive
1489     *                  numbers mean that the finger/cursor is moving down the screen,
1490     *                  which means we want to scroll towards the left.
1491     */
1492    public void fling(int velocityX) {
1493        if (getChildCount() > 0) {
1494            int width = getWidth() - mPaddingRight - mPaddingLeft;
1495            int right = getChildAt(0).getWidth();
1496
1497            mScroller.fling(mScrollX, mScrollY, velocityX, 0, 0,
1498                    Math.max(0, right - width), 0, 0, width/2, 0);
1499
1500            final boolean movingRight = velocityX > 0;
1501
1502            View currentFocused = findFocus();
1503            View newFocused = findFocusableViewInMyBounds(movingRight,
1504                    mScroller.getFinalX(), currentFocused);
1505
1506            if (newFocused == null) {
1507                newFocused = this;
1508            }
1509
1510            if (newFocused != currentFocused) {
1511                newFocused.requestFocus(movingRight ? View.FOCUS_RIGHT : View.FOCUS_LEFT);
1512            }
1513
1514            postInvalidateOnAnimation();
1515        }
1516    }
1517
1518    /**
1519     * {@inheritDoc}
1520     *
1521     * <p>This version also clamps the scrolling to the bounds of our child.
1522     */
1523    @Override
1524    public void scrollTo(int x, int y) {
1525        // we rely on the fact the View.scrollBy calls scrollTo.
1526        if (getChildCount() > 0) {
1527            View child = getChildAt(0);
1528            x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1529            y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1530            if (x != mScrollX || y != mScrollY) {
1531                super.scrollTo(x, y);
1532            }
1533        }
1534    }
1535
1536    @Override
1537    public void setOverScrollMode(int mode) {
1538        if (mode != OVER_SCROLL_NEVER) {
1539            if (mEdgeGlowLeft == null) {
1540                Context context = getContext();
1541                mEdgeGlowLeft = new EdgeEffect(context);
1542                mEdgeGlowRight = new EdgeEffect(context);
1543            }
1544        } else {
1545            mEdgeGlowLeft = null;
1546            mEdgeGlowRight = null;
1547        }
1548        super.setOverScrollMode(mode);
1549    }
1550
1551    @SuppressWarnings({"SuspiciousNameCombination"})
1552    @Override
1553    public void draw(Canvas canvas) {
1554        super.draw(canvas);
1555        if (mEdgeGlowLeft != null) {
1556            final int scrollX = mScrollX;
1557            if (!mEdgeGlowLeft.isFinished()) {
1558                final int restoreCount = canvas.save();
1559                final int height = getHeight() - mPaddingTop - mPaddingBottom;
1560
1561                canvas.rotate(270);
1562                canvas.translate(-height + mPaddingTop, Math.min(0, scrollX));
1563                mEdgeGlowLeft.setSize(height, getWidth());
1564                if (mEdgeGlowLeft.draw(canvas)) {
1565                    postInvalidateOnAnimation();
1566                }
1567                canvas.restoreToCount(restoreCount);
1568            }
1569            if (!mEdgeGlowRight.isFinished()) {
1570                final int restoreCount = canvas.save();
1571                final int width = getWidth();
1572                final int height = getHeight() - mPaddingTop - mPaddingBottom;
1573
1574                canvas.rotate(90);
1575                canvas.translate(-mPaddingTop,
1576                        -(Math.max(getScrollRange(), scrollX) + width));
1577                mEdgeGlowRight.setSize(height, width);
1578                if (mEdgeGlowRight.draw(canvas)) {
1579                    postInvalidateOnAnimation();
1580                }
1581                canvas.restoreToCount(restoreCount);
1582            }
1583        }
1584    }
1585
1586    private static int clamp(int n, int my, int child) {
1587        if (my >= child || n < 0) {
1588            return 0;
1589        }
1590        if ((my + n) > child) {
1591            return child - my;
1592        }
1593        return n;
1594    }
1595}
1596