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