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