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