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