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