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