HorizontalScrollView.java revision fdbf484be1eca388553d97a13a9500b98b18b474
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.Rect;
22import android.util.AttributeSet;
23import android.view.FocusFinder;
24import android.view.KeyEvent;
25import android.view.MotionEvent;
26import android.view.VelocityTracker;
27import android.view.View;
28import android.view.ViewConfiguration;
29import android.view.ViewGroup;
30import android.view.ViewParent;
31import android.view.animation.AnimationUtils;
32
33import java.util.List;
34
35/**
36 * Layout container for a view hierarchy that can be scrolled by the user,
37 * allowing it to be larger than the physical display.  A HorizontalScrollView
38 * is a {@link FrameLayout}, meaning you should place one child in it
39 * containing the entire contents to scroll; this child may itself be a layout
40 * manager with a complex hierarchy of objects.  A child that is often used
41 * is a {@link LinearLayout} in a horizontal orientation, presenting a horizontal
42 * array of top-level items that the user can scroll through.
43 *
44 * <p>You should never use a HorizontalScrollView with a {@link ListView}, since
45 * ListView takes care of its own scrolling.  Most importantly, doing this
46 * defeats all of the important optimizations in ListView for dealing with
47 * large lists, since it effectively forces the ListView to display its entire
48 * list of items to fill up the infinite container supplied by HorizontalScrollView.
49 *
50 * <p>The {@link TextView} class also
51 * takes care of its own scrolling, so does not require a ScrollView, 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.
56 *
57 * @attr ref android.R.styleable#HorizontalScrollView_fillViewport
58 */
59public class HorizontalScrollView extends FrameLayout {
60    private static final int ANIMATED_SCROLL_GAP = ScrollView.ANIMATED_SCROLL_GAP;
61
62    private static final float MAX_SCROLL_FACTOR = ScrollView.MAX_SCROLL_FACTOR;
63
64
65    private long mLastScroll;
66
67    private final Rect mTempRect = new Rect();
68    private Scroller mScroller;
69
70    /**
71     * Flag to indicate that we are moving focus ourselves. This is so the
72     * code that watches for focus changes initiated outside this ScrollView
73     * knows that it does not have to do anything.
74     */
75    private boolean mScrollViewMovedFocus;
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    private boolean mFillViewport;
112
113    /**
114     * Whether arrow scrolling is animated.
115     */
116    private boolean mSmoothScrollingEnabled = true;
117
118    private int mTouchSlop;
119    private int mMinimumVelocity;
120    private int mMaximumVelocity;
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 Scroller(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    }
203
204    @Override
205    public void addView(View child) {
206        if (getChildCount() > 0) {
207            throw new IllegalStateException("HorizontalScrollView can host only one direct child");
208        }
209
210        super.addView(child);
211    }
212
213    @Override
214    public void addView(View child, int index) {
215        if (getChildCount() > 0) {
216            throw new IllegalStateException("HorizontalScrollView can host only one direct child");
217        }
218
219        super.addView(child, index);
220    }
221
222    @Override
223    public void addView(View child, ViewGroup.LayoutParams params) {
224        if (getChildCount() > 0) {
225            throw new IllegalStateException("HorizontalScrollView can host only one direct child");
226        }
227
228        super.addView(child, params);
229    }
230
231    @Override
232    public void addView(View child, int index, ViewGroup.LayoutParams params) {
233        if (getChildCount() > 0) {
234            throw new IllegalStateException("HorizontalScrollView can host only one direct child");
235        }
236
237        super.addView(child, index, params);
238    }
239
240    /**
241     * @return Returns true this HorizontalScrollView can be scrolled
242     */
243    private boolean canScroll() {
244        View child = getChildAt(0);
245        if (child != null) {
246            int childWidth = child.getWidth();
247            return getWidth() < childWidth + mPaddingLeft + mPaddingRight ;
248        }
249        return false;
250    }
251
252    /**
253     * Indicates whether this HorizontalScrollView's content is stretched to
254     * fill the viewport.
255     *
256     * @return True if the content fills the viewport, false otherwise.
257     *
258     * @attr ref android.R.styleable#HorizontalScrollView_fillViewport
259     */
260    public boolean isFillViewport() {
261        return mFillViewport;
262    }
263
264    /**
265     * Indicates this HorizontalScrollView whether it should stretch its content width
266     * to fill the viewport or not.
267     *
268     * @param fillViewport True to stretch the content's width to the viewport's
269     *        boundaries, false otherwise.
270     *
271     * @attr ref android.R.styleable#HorizontalScrollView_fillViewport
272     */
273    public void setFillViewport(boolean fillViewport) {
274        if (fillViewport != mFillViewport) {
275            mFillViewport = fillViewport;
276            requestLayout();
277        }
278    }
279
280    /**
281     * @return Whether arrow scrolling will animate its transition.
282     */
283    public boolean isSmoothScrollingEnabled() {
284        return mSmoothScrollingEnabled;
285    }
286
287    /**
288     * Set whether arrow scrolling will animate its transition.
289     * @param smoothScrollingEnabled whether arrow scrolling will animate its transition
290     */
291    public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) {
292        mSmoothScrollingEnabled = smoothScrollingEnabled;
293    }
294
295    @Override
296    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
297        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
298
299        if (!mFillViewport) {
300            return;
301        }
302
303        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
304        if (widthMode == MeasureSpec.UNSPECIFIED) {
305            return;
306        }
307
308        if (getChildCount() > 0) {
309            final View child = getChildAt(0);
310            int width = getMeasuredWidth();
311            if (child.getMeasuredWidth() < width) {
312                final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams();
313
314                int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, mPaddingTop
315                        + mPaddingBottom, lp.height);
316                width -= mPaddingLeft;
317                width -= mPaddingRight;
318                int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
319
320                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
321            }
322        }
323    }
324
325    @Override
326    public boolean dispatchKeyEvent(KeyEvent event) {
327        // Let the focused view and/or our descendants get the key first
328        return super.dispatchKeyEvent(event) || executeKeyEvent(event);
329    }
330
331    /**
332     * You can call this function yourself to have the scroll view perform
333     * scrolling from a key event, just as if the event had been dispatched to
334     * it by the view hierarchy.
335     *
336     * @param event The key event to execute.
337     * @return Return true if the event was handled, else false.
338     */
339    public boolean executeKeyEvent(KeyEvent event) {
340        mTempRect.setEmpty();
341
342        if (!canScroll()) {
343            if (isFocused()) {
344                View currentFocused = findFocus();
345                if (currentFocused == this) currentFocused = null;
346                View nextFocused = FocusFinder.getInstance().findNextFocus(this,
347                        currentFocused, View.FOCUS_RIGHT);
348                return nextFocused != null && nextFocused != this &&
349                        nextFocused.requestFocus(View.FOCUS_RIGHT);
350            }
351            return false;
352        }
353
354        boolean handled = false;
355        if (event.getAction() == KeyEvent.ACTION_DOWN) {
356            switch (event.getKeyCode()) {
357                case KeyEvent.KEYCODE_DPAD_LEFT:
358                    if (!event.isAltPressed()) {
359                        handled = arrowScroll(View.FOCUS_LEFT);
360                    } else {
361                        handled = fullScroll(View.FOCUS_LEFT);
362                    }
363                    break;
364                case KeyEvent.KEYCODE_DPAD_RIGHT:
365                    if (!event.isAltPressed()) {
366                        handled = arrowScroll(View.FOCUS_RIGHT);
367                    } else {
368                        handled = fullScroll(View.FOCUS_RIGHT);
369                    }
370                    break;
371                case KeyEvent.KEYCODE_SPACE:
372                    pageScroll(event.isShiftPressed() ? View.FOCUS_LEFT : View.FOCUS_RIGHT);
373                    break;
374            }
375        }
376
377        return handled;
378    }
379
380    private boolean inChild(int x, int y) {
381        if (getChildCount() > 0) {
382            final int scrollX = mScrollX;
383            final View child = getChildAt(0);
384            return !(y < child.getTop()
385                    || y >= child.getBottom()
386                    || x < child.getLeft() - scrollX
387                    || x >= child.getRight() - scrollX);
388        }
389        return false;
390    }
391
392    @Override
393    public boolean onInterceptTouchEvent(MotionEvent ev) {
394        /*
395         * This method JUST determines whether we want to intercept the motion.
396         * If we return true, onMotionEvent will be called and we do the actual
397         * scrolling there.
398         */
399
400        /*
401        * Shortcut the most recurring case: the user is in the dragging
402        * state and he is moving his finger.  We want to intercept this
403        * motion.
404        */
405        final int action = ev.getAction();
406        if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
407            return true;
408        }
409
410        switch (action & MotionEvent.ACTION_MASK) {
411            case MotionEvent.ACTION_MOVE: {
412                /*
413                 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
414                 * whether the user has moved far enough from his original down touch.
415                 */
416
417                /*
418                * Locally do absolute value. mLastMotionX is set to the x value
419                * of the down event.
420                */
421                final int activePointerId = mActivePointerId;
422                if (activePointerId == INVALID_POINTER) {
423                    // If we don't have a valid id, the touch down wasn't on content.
424                    break;
425                }
426
427                final int pointerIndex = ev.findPointerIndex(activePointerId);
428                final float x = ev.getX(pointerIndex);
429                final int xDiff = (int) Math.abs(x - mLastMotionX);
430                if (xDiff > mTouchSlop) {
431                    mIsBeingDragged = true;
432                    mLastMotionX = x;
433                    if (mParent != null) mParent.requestDisallowInterceptTouchEvent(true);
434                }
435                break;
436            }
437
438            case MotionEvent.ACTION_DOWN: {
439                final float x = ev.getX();
440                if (!inChild((int) x, (int) ev.getY())) {
441                    mIsBeingDragged = false;
442                    break;
443                }
444
445                /*
446                 * Remember location of down touch.
447                 * ACTION_DOWN always refers to pointer index 0.
448                 */
449                mLastMotionX = x;
450                mActivePointerId = ev.getPointerId(0);
451
452                /*
453                * If being flinged and user touches the screen, initiate drag;
454                * otherwise don't.  mScroller.isFinished should be false when
455                * being flinged.
456                */
457                mIsBeingDragged = !mScroller.isFinished();
458                break;
459            }
460
461            case MotionEvent.ACTION_CANCEL:
462            case MotionEvent.ACTION_UP:
463                /* Release the drag */
464                mIsBeingDragged = false;
465                mActivePointerId = INVALID_POINTER;
466                break;
467            case MotionEvent.ACTION_POINTER_UP:
468                onSecondaryPointerUp(ev);
469                break;
470        }
471
472        /*
473        * The only time we want to intercept motion events is if we are in the
474        * drag mode.
475        */
476        return mIsBeingDragged;
477    }
478
479    @Override
480    public boolean onTouchEvent(MotionEvent ev) {
481
482        if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
483            // Don't handle edge touches immediately -- they may actually belong to one of our
484            // descendants.
485            return false;
486        }
487
488        if (mVelocityTracker == null) {
489            mVelocityTracker = VelocityTracker.obtain();
490        }
491        mVelocityTracker.addMovement(ev);
492
493        final int action = ev.getAction();
494
495        switch (action & MotionEvent.ACTION_MASK) {
496            case MotionEvent.ACTION_DOWN: {
497                final float x = ev.getX();
498                if (!(mIsBeingDragged = inChild((int) x, (int) ev.getY()))) {
499                    return false;
500                }
501
502                /*
503                 * If being flinged and user touches, stop the fling. isFinished
504                 * will be false if being flinged.
505                 */
506                if (!mScroller.isFinished()) {
507                    mScroller.abortAnimation();
508                }
509
510                // Remember where the motion event started
511                mLastMotionX = x;
512                mActivePointerId = ev.getPointerId(0);
513                break;
514            }
515            case MotionEvent.ACTION_MOVE:
516                if (mIsBeingDragged) {
517                    // Scroll to follow the motion event
518                    final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
519                    final float x = ev.getX(activePointerIndex);
520                    final int deltaX = (int) (mLastMotionX - x);
521                    mLastMotionX = x;
522
523                    scrollBy(deltaX, 0);
524                }
525                break;
526            case MotionEvent.ACTION_UP:
527                if (mIsBeingDragged) {
528                    final VelocityTracker velocityTracker = mVelocityTracker;
529                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
530                    int initialVelocity = (int) velocityTracker.getXVelocity(mActivePointerId);
531
532                    if (getChildCount() > 0 && Math.abs(initialVelocity) > mMinimumVelocity) {
533                        fling(-initialVelocity);
534                    }
535
536                    mActivePointerId = INVALID_POINTER;
537                    mIsBeingDragged = false;
538
539                    if (mVelocityTracker != null) {
540                        mVelocityTracker.recycle();
541                        mVelocityTracker = null;
542                    }
543                }
544                break;
545            case MotionEvent.ACTION_CANCEL:
546                if (mIsBeingDragged && getChildCount() > 0) {
547                    mActivePointerId = INVALID_POINTER;
548                    mIsBeingDragged = false;
549                    if (mVelocityTracker != null) {
550                        mVelocityTracker.recycle();
551                        mVelocityTracker = null;
552                    }
553                }
554                break;
555            case MotionEvent.ACTION_POINTER_UP:
556                onSecondaryPointerUp(ev);
557                break;
558        }
559        return true;
560    }
561
562    private void onSecondaryPointerUp(MotionEvent ev) {
563        final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
564                MotionEvent.ACTION_POINTER_INDEX_SHIFT;
565        final int pointerId = ev.getPointerId(pointerIndex);
566        if (pointerId == mActivePointerId) {
567            // This was our active pointer going up. Choose a new
568            // active pointer and adjust accordingly.
569            // TODO: Make this decision more intelligent.
570            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
571            mLastMotionX = ev.getX(newPointerIndex);
572            mActivePointerId = ev.getPointerId(newPointerIndex);
573            if (mVelocityTracker != null) {
574                mVelocityTracker.clear();
575            }
576        }
577    }
578
579    private int getScrollRange() {
580        int scrollRange = 0;
581        if (getChildCount() > 0) {
582            View child = getChildAt(0);
583            scrollRange = Math.max(0,
584                    child.getWidth() - getWidth() - mPaddingLeft - mPaddingRight);
585        }
586        return scrollRange;
587    }
588
589    /**
590     * <p>
591     * Finds the next focusable component that fits in this View's bounds
592     * (excluding fading edges) pretending that this View's left is located at
593     * the parameter left.
594     * </p>
595     *
596     * @param leftFocus          look for a candidate is the one at the left of the bounds
597     *                           if leftFocus is true, or at the right of the bounds if leftFocus
598     *                           is false
599     * @param left               the left offset of the bounds in which a focusable must be
600     *                           found (the fading edge is assumed to start at this position)
601     * @param preferredFocusable the View that has highest priority and will be
602     *                           returned if it is within my bounds (null is valid)
603     * @return the next focusable component in the bounds or null if none can be found
604     */
605    private View findFocusableViewInMyBounds(final boolean leftFocus,
606            final int left, View preferredFocusable) {
607        /*
608         * The fading edge's transparent side should be considered for focus
609         * since it's mostly visible, so we divide the actual fading edge length
610         * by 2.
611         */
612        final int fadingEdgeLength = getHorizontalFadingEdgeLength() / 2;
613        final int leftWithoutFadingEdge = left + fadingEdgeLength;
614        final int rightWithoutFadingEdge = left + getWidth() - fadingEdgeLength;
615
616        if ((preferredFocusable != null)
617                && (preferredFocusable.getLeft() < rightWithoutFadingEdge)
618                && (preferredFocusable.getRight() > leftWithoutFadingEdge)) {
619            return preferredFocusable;
620        }
621
622        return findFocusableViewInBounds(leftFocus, leftWithoutFadingEdge,
623                rightWithoutFadingEdge);
624    }
625
626    /**
627     * <p>
628     * Finds the next focusable component that fits in the specified bounds.
629     * </p>
630     *
631     * @param leftFocus look for a candidate is the one at the left of the bounds
632     *                  if leftFocus is true, or at the right of the bounds if
633     *                  leftFocus is false
634     * @param left      the left offset of the bounds in which a focusable must be
635     *                  found
636     * @param right     the right offset of the bounds in which a focusable must
637     *                  be found
638     * @return the next focusable component in the bounds or null if none can
639     *         be found
640     */
641    private View findFocusableViewInBounds(boolean leftFocus, int left, int right) {
642
643        List<View> focusables = getFocusables(View.FOCUS_FORWARD);
644        View focusCandidate = null;
645
646        /*
647         * A fully contained focusable is one where its left is below the bound's
648         * left, and its right is above the bound's right. A partially
649         * contained focusable is one where some part of it is within the
650         * bounds, but it also has some part that is not within bounds.  A fully contained
651         * focusable is preferred to a partially contained focusable.
652         */
653        boolean foundFullyContainedFocusable = false;
654
655        int count = focusables.size();
656        for (int i = 0; i < count; i++) {
657            View view = focusables.get(i);
658            int viewLeft = view.getLeft();
659            int viewRight = view.getRight();
660
661            if (left < viewRight && viewLeft < right) {
662                /*
663                 * the focusable is in the target area, it is a candidate for
664                 * focusing
665                 */
666
667                final boolean viewIsFullyContained = (left < viewLeft) &&
668                        (viewRight < right);
669
670                if (focusCandidate == null) {
671                    /* No candidate, take this one */
672                    focusCandidate = view;
673                    foundFullyContainedFocusable = viewIsFullyContained;
674                } else {
675                    final boolean viewIsCloserToBoundary =
676                            (leftFocus && viewLeft < focusCandidate.getLeft()) ||
677                                    (!leftFocus && viewRight > focusCandidate.getRight());
678
679                    if (foundFullyContainedFocusable) {
680                        if (viewIsFullyContained && viewIsCloserToBoundary) {
681                            /*
682                             * We're dealing with only fully contained views, so
683                             * it has to be closer to the boundary to beat our
684                             * candidate
685                             */
686                            focusCandidate = view;
687                        }
688                    } else {
689                        if (viewIsFullyContained) {
690                            /* Any fully contained view beats a partially contained view */
691                            focusCandidate = view;
692                            foundFullyContainedFocusable = true;
693                        } else if (viewIsCloserToBoundary) {
694                            /*
695                             * Partially contained view beats another partially
696                             * contained view if it's closer
697                             */
698                            focusCandidate = view;
699                        }
700                    }
701                }
702            }
703        }
704
705        return focusCandidate;
706    }
707
708    /**
709     * <p>Handles scrolling in response to a "page up/down" shortcut press. This
710     * method will scroll the view by one page left or right and give the focus
711     * to the leftmost/rightmost component in the new visible area. If no
712     * component is a good candidate for focus, this scrollview reclaims the
713     * focus.</p>
714     *
715     * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT}
716     *                  to go one page left or {@link android.view.View#FOCUS_RIGHT}
717     *                  to go one page right
718     * @return true if the key event is consumed by this method, false otherwise
719     */
720    public boolean pageScroll(int direction) {
721        boolean right = direction == View.FOCUS_RIGHT;
722        int width = getWidth();
723
724        if (right) {
725            mTempRect.left = getScrollX() + width;
726            int count = getChildCount();
727            if (count > 0) {
728                View view = getChildAt(0);
729                if (mTempRect.left + width > view.getRight()) {
730                    mTempRect.left = view.getRight() - width;
731                }
732            }
733        } else {
734            mTempRect.left = getScrollX() - width;
735            if (mTempRect.left < 0) {
736                mTempRect.left = 0;
737            }
738        }
739        mTempRect.right = mTempRect.left + width;
740
741        return scrollAndFocus(direction, mTempRect.left, mTempRect.right);
742    }
743
744    /**
745     * <p>Handles scrolling in response to a "home/end" shortcut press. This
746     * method will scroll the view to the left or right and give the focus
747     * to the leftmost/rightmost component in the new visible area. If no
748     * component is a good candidate for focus, this scrollview reclaims the
749     * focus.</p>
750     *
751     * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT}
752     *                  to go the left of the view or {@link android.view.View#FOCUS_RIGHT}
753     *                  to go the right
754     * @return true if the key event is consumed by this method, false otherwise
755     */
756    public boolean fullScroll(int direction) {
757        boolean right = direction == View.FOCUS_RIGHT;
758        int width = getWidth();
759
760        mTempRect.left = 0;
761        mTempRect.right = width;
762
763        if (right) {
764            int count = getChildCount();
765            if (count > 0) {
766                View view = getChildAt(0);
767                mTempRect.right = view.getRight();
768                mTempRect.left = mTempRect.right - width;
769            }
770        }
771
772        return scrollAndFocus(direction, mTempRect.left, mTempRect.right);
773    }
774
775    /**
776     * <p>Scrolls the view to make the area defined by <code>left</code> and
777     * <code>right</code> visible. This method attempts to give the focus
778     * to a component visible in this area. If no component can be focused in
779     * the new visible area, the focus is reclaimed by this scrollview.</p>
780     *
781     * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT}
782     *                  to go left {@link android.view.View#FOCUS_RIGHT} to right
783     * @param left     the left offset of the new area to be made visible
784     * @param right    the right offset of the new area to be made visible
785     * @return true if the key event is consumed by this method, false otherwise
786     */
787    private boolean scrollAndFocus(int direction, int left, int right) {
788        boolean handled = true;
789
790        int width = getWidth();
791        int containerLeft = getScrollX();
792        int containerRight = containerLeft + width;
793        boolean goLeft = direction == View.FOCUS_LEFT;
794
795        View newFocused = findFocusableViewInBounds(goLeft, left, right);
796        if (newFocused == null) {
797            newFocused = this;
798        }
799
800        if (left >= containerLeft && right <= containerRight) {
801            handled = false;
802        } else {
803            int delta = goLeft ? (left - containerLeft) : (right - containerRight);
804            doScrollX(delta);
805        }
806
807        if (newFocused != findFocus() && newFocused.requestFocus(direction)) {
808            mScrollViewMovedFocus = true;
809            mScrollViewMovedFocus = false;
810        }
811
812        return handled;
813    }
814
815    /**
816     * Handle scrolling in response to a left or right arrow click.
817     *
818     * @param direction The direction corresponding to the arrow key that was
819     *                  pressed
820     * @return True if we consumed the event, false otherwise
821     */
822    public boolean arrowScroll(int direction) {
823
824        View currentFocused = findFocus();
825        if (currentFocused == this) currentFocused = null;
826
827        View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
828
829        final int maxJump = getMaxScrollAmount();
830
831        if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump)) {
832            nextFocused.getDrawingRect(mTempRect);
833            offsetDescendantRectToMyCoords(nextFocused, mTempRect);
834            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
835            doScrollX(scrollDelta);
836            nextFocused.requestFocus(direction);
837        } else {
838            // no new focus
839            int scrollDelta = maxJump;
840
841            if (direction == View.FOCUS_LEFT && getScrollX() < scrollDelta) {
842                scrollDelta = getScrollX();
843            } else if (direction == View.FOCUS_RIGHT && getChildCount() > 0) {
844
845                int daRight = getChildAt(0).getRight();
846
847                int screenRight = getScrollX() + getWidth();
848
849                if (daRight - screenRight < maxJump) {
850                    scrollDelta = daRight - screenRight;
851                }
852            }
853            if (scrollDelta == 0) {
854                return false;
855            }
856            doScrollX(direction == View.FOCUS_RIGHT ? scrollDelta : -scrollDelta);
857        }
858
859        if (currentFocused != null && currentFocused.isFocused()
860                && isOffScreen(currentFocused)) {
861            // previously focused item still has focus and is off screen, give
862            // it up (take it back to ourselves)
863            // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
864            // sure to
865            // get it)
866            final int descendantFocusability = getDescendantFocusability();  // save
867            setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
868            requestFocus();
869            setDescendantFocusability(descendantFocusability);  // restore
870        }
871        return true;
872    }
873
874    /**
875     * @return whether the descendant of this scroll view is scrolled off
876     *  screen.
877     */
878    private boolean isOffScreen(View descendant) {
879        return !isWithinDeltaOfScreen(descendant, 0);
880    }
881
882    /**
883     * @return whether the descendant of this scroll view is within delta
884     *  pixels of being on the screen.
885     */
886    private boolean isWithinDeltaOfScreen(View descendant, int delta) {
887        descendant.getDrawingRect(mTempRect);
888        offsetDescendantRectToMyCoords(descendant, mTempRect);
889
890        return (mTempRect.right + delta) >= getScrollX()
891                && (mTempRect.left - delta) <= (getScrollX() + getWidth());
892    }
893
894    /**
895     * Smooth scroll by a X delta
896     *
897     * @param delta the number of pixels to scroll by on the X axis
898     */
899    private void doScrollX(int delta) {
900        if (delta != 0) {
901            if (mSmoothScrollingEnabled) {
902                smoothScrollBy(delta, 0);
903            } else {
904                scrollBy(delta, 0);
905            }
906        }
907    }
908
909    /**
910     * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
911     *
912     * @param dx the number of pixels to scroll by on the X axis
913     * @param dy the number of pixels to scroll by on the Y axis
914     */
915    public final void smoothScrollBy(int dx, int dy) {
916        if (getChildCount() == 0) {
917            // Nothing to do.
918            return;
919        }
920        long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
921        if (duration > ANIMATED_SCROLL_GAP) {
922            final int width = getWidth() - mPaddingRight - mPaddingLeft;
923            final int right = getChildAt(0).getWidth();
924            final int maxX = Math.max(0, right - width);
925            final int scrollX = mScrollX;
926            dx = Math.max(0, Math.min(scrollX + dx, maxX)) - scrollX;
927
928            mScroller.startScroll(scrollX, mScrollY, dx, 0);
929            invalidate();
930        } else {
931            if (!mScroller.isFinished()) {
932                mScroller.abortAnimation();
933            }
934            scrollBy(dx, dy);
935        }
936        mLastScroll = AnimationUtils.currentAnimationTimeMillis();
937    }
938
939    /**
940     * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
941     *
942     * @param x the position where to scroll on the X axis
943     * @param y the position where to scroll on the Y axis
944     */
945    public final void smoothScrollTo(int x, int y) {
946        smoothScrollBy(x - mScrollX, y - mScrollY);
947    }
948
949    /**
950     * <p>The scroll range of a scroll view is the overall width of all of its
951     * children.</p>
952     */
953    @Override
954    protected int computeHorizontalScrollRange() {
955        final int count = getChildCount();
956        final int contentWidth = getWidth() - mPaddingLeft - mPaddingRight;
957        if (count == 0) {
958            return contentWidth;
959        }
960
961        return getChildAt(0).getRight();
962    }
963
964    @Override
965    protected int computeHorizontalScrollOffset() {
966        return Math.max(0, super.computeHorizontalScrollOffset());
967    }
968
969    @Override
970    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
971        ViewGroup.LayoutParams lp = child.getLayoutParams();
972
973        int childWidthMeasureSpec;
974        int childHeightMeasureSpec;
975
976        childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop
977                + mPaddingBottom, lp.height);
978
979        childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
980
981        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
982    }
983
984    @Override
985    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
986            int parentHeightMeasureSpec, int heightUsed) {
987        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
988
989        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
990                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
991                        + heightUsed, lp.height);
992        final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
993                lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);
994
995        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
996    }
997
998    @Override
999    public void computeScroll() {
1000        if (mScroller.computeScrollOffset()) {
1001            // This is called at drawing time by ViewGroup.  We don't want to
1002            // re-show the scrollbars at this point, which scrollTo will do,
1003            // so we replicate most of scrollTo here.
1004            //
1005            //         It's a little odd to call onScrollChanged from inside the drawing.
1006            //
1007            //         It is, except when you remember that computeScroll() is used to
1008            //         animate scrolling. So unless we want to defer the onScrollChanged()
1009            //         until the end of the animated scrolling, we don't really have a
1010            //         choice here.
1011            //
1012            //         I agree.  The alternative, which I think would be worse, is to post
1013            //         something and tell the subclasses later.  This is bad because there
1014            //         will be a window where mScrollX/Y is different from what the app
1015            //         thinks it is.
1016            //
1017            int oldX = mScrollX;
1018            int oldY = mScrollY;
1019            int x = mScroller.getCurrX();
1020            int y = mScroller.getCurrY();
1021
1022            if (getChildCount() > 0) {
1023                View child = getChildAt(0);
1024                x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1025                y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1026                if (x != oldX || y != oldY) {
1027                    mScrollX = x;
1028                    mScrollY = y;
1029                    onScrollChanged(x, y, oldX, oldY);
1030                }
1031            }
1032            awakenScrollBars();
1033
1034            // Keep on drawing until the animation has finished.
1035            postInvalidate();
1036        }
1037    }
1038
1039    /**
1040     * Scrolls the view to the given child.
1041     *
1042     * @param child the View to scroll to
1043     */
1044    private void scrollToChild(View child) {
1045        child.getDrawingRect(mTempRect);
1046
1047        /* Offset from child's local coordinates to ScrollView coordinates */
1048        offsetDescendantRectToMyCoords(child, mTempRect);
1049
1050        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1051
1052        if (scrollDelta != 0) {
1053            scrollBy(scrollDelta, 0);
1054        }
1055    }
1056
1057    /**
1058     * If rect is off screen, scroll just enough to get it (or at least the
1059     * first screen size chunk of it) on screen.
1060     *
1061     * @param rect      The rectangle.
1062     * @param immediate True to scroll immediately without animation
1063     * @return true if scrolling was performed
1064     */
1065    private boolean scrollToChildRect(Rect rect, boolean immediate) {
1066        final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
1067        final boolean scroll = delta != 0;
1068        if (scroll) {
1069            if (immediate) {
1070                scrollBy(delta, 0);
1071            } else {
1072                smoothScrollBy(delta, 0);
1073            }
1074        }
1075        return scroll;
1076    }
1077
1078    /**
1079     * Compute the amount to scroll in the X direction in order to get
1080     * a rectangle completely on the screen (or, if taller than the screen,
1081     * at least the first screen size chunk of it).
1082     *
1083     * @param rect The rect.
1084     * @return The scroll delta.
1085     */
1086    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
1087        if (getChildCount() == 0) return 0;
1088
1089        int width = getWidth();
1090        int screenLeft = getScrollX();
1091        int screenRight = screenLeft + width;
1092
1093        int fadingEdge = getHorizontalFadingEdgeLength();
1094
1095        // leave room for left fading edge as long as rect isn't at very left
1096        if (rect.left > 0) {
1097            screenLeft += fadingEdge;
1098        }
1099
1100        // leave room for right fading edge as long as rect isn't at very right
1101        if (rect.right < getChildAt(0).getWidth()) {
1102            screenRight -= fadingEdge;
1103        }
1104
1105        int scrollXDelta = 0;
1106
1107        if (rect.right > screenRight && rect.left > screenLeft) {
1108            // need to move right to get it in view: move right just enough so
1109            // that the entire rectangle is in view (or at least the first
1110            // screen size chunk).
1111
1112            if (rect.width() > width) {
1113                // just enough to get screen size chunk on
1114                scrollXDelta += (rect.left - screenLeft);
1115            } else {
1116                // get entire rect at right of screen
1117                scrollXDelta += (rect.right - screenRight);
1118            }
1119
1120            // make sure we aren't scrolling beyond the end of our content
1121            int right = getChildAt(0).getRight();
1122            int distanceToRight = right - screenRight;
1123            scrollXDelta = Math.min(scrollXDelta, distanceToRight);
1124
1125        } else if (rect.left < screenLeft && rect.right < screenRight) {
1126            // need to move right to get it in view: move right just enough so that
1127            // entire rectangle is in view (or at least the first screen
1128            // size chunk of it).
1129
1130            if (rect.width() > width) {
1131                // screen size chunk
1132                scrollXDelta -= (screenRight - rect.right);
1133            } else {
1134                // entire rect at left
1135                scrollXDelta -= (screenLeft - rect.left);
1136            }
1137
1138            // make sure we aren't scrolling any further than the left our content
1139            scrollXDelta = Math.max(scrollXDelta, -getScrollX());
1140        }
1141        return scrollXDelta;
1142    }
1143
1144    @Override
1145    public void requestChildFocus(View child, View focused) {
1146        if (!mScrollViewMovedFocus) {
1147            if (!mIsLayoutDirty) {
1148                scrollToChild(focused);
1149            } else {
1150                // The child may not be laid out yet, we can't compute the scroll yet
1151                mChildToScrollTo = focused;
1152            }
1153        }
1154        super.requestChildFocus(child, focused);
1155    }
1156
1157
1158    /**
1159     * When looking for focus in children of a scroll view, need to be a little
1160     * more careful not to give focus to something that is scrolled off screen.
1161     *
1162     * This is more expensive than the default {@link android.view.ViewGroup}
1163     * implementation, otherwise this behavior might have been made the default.
1164     */
1165    @Override
1166    protected boolean onRequestFocusInDescendants(int direction,
1167            Rect previouslyFocusedRect) {
1168
1169        // convert from forward / backward notation to up / down / left / right
1170        // (ugh).
1171        if (direction == View.FOCUS_FORWARD) {
1172            direction = View.FOCUS_RIGHT;
1173        } else if (direction == View.FOCUS_BACKWARD) {
1174            direction = View.FOCUS_LEFT;
1175        }
1176
1177        final View nextFocus = previouslyFocusedRect == null ?
1178                FocusFinder.getInstance().findNextFocus(this, null, direction) :
1179                FocusFinder.getInstance().findNextFocusFromRect(this,
1180                        previouslyFocusedRect, direction);
1181
1182        if (nextFocus == null) {
1183            return false;
1184        }
1185
1186        if (isOffScreen(nextFocus)) {
1187            return false;
1188        }
1189
1190        return nextFocus.requestFocus(direction, previouslyFocusedRect);
1191    }
1192
1193    @Override
1194    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1195            boolean immediate) {
1196        // offset into coordinate space of this scroll view
1197        rectangle.offset(child.getLeft() - child.getScrollX(),
1198                child.getTop() - child.getScrollY());
1199
1200        return scrollToChildRect(rectangle, immediate);
1201    }
1202
1203    @Override
1204    public void requestLayout() {
1205        mIsLayoutDirty = true;
1206        super.requestLayout();
1207    }
1208
1209    @Override
1210    protected void onLayout(boolean changed, int l, int t, int r, int b) {
1211        super.onLayout(changed, l, t, r, b);
1212        mIsLayoutDirty = false;
1213        // Give a child focus if it needs it
1214        if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1215                scrollToChild(mChildToScrollTo);
1216        }
1217        mChildToScrollTo = null;
1218
1219        // Calling this with the present values causes it to re-clam them
1220        scrollTo(mScrollX, mScrollY);
1221    }
1222
1223    @Override
1224    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1225        super.onSizeChanged(w, h, oldw, oldh);
1226
1227        View currentFocused = findFocus();
1228        if (null == currentFocused || this == currentFocused)
1229            return;
1230
1231        final int maxJump = mRight - mLeft;
1232
1233        if (isWithinDeltaOfScreen(currentFocused, maxJump)) {
1234            currentFocused.getDrawingRect(mTempRect);
1235            offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1236            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1237            doScrollX(scrollDelta);
1238        }
1239    }
1240
1241    /**
1242     * Return true if child is an descendant of parent, (or equal to the parent).
1243     */
1244    private boolean isViewDescendantOf(View child, View parent) {
1245        if (child == parent) {
1246            return true;
1247        }
1248
1249        final ViewParent theParent = child.getParent();
1250        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1251    }
1252
1253    /**
1254     * Fling the scroll view
1255     *
1256     * @param velocityX The initial velocity in the X direction. Positive
1257     *                  numbers mean that the finger/curor is moving down the screen,
1258     *                  which means we want to scroll towards the left.
1259     */
1260    public void fling(int velocityX) {
1261        if (getChildCount() > 0) {
1262            int width = getWidth() - mPaddingRight - mPaddingLeft;
1263            int right = getChildAt(0).getWidth();
1264
1265            mScroller.fling(mScrollX, mScrollY, velocityX, 0, 0,
1266                    Math.max(0, right - width), 0, 0);
1267
1268            final boolean movingRight = velocityX > 0;
1269
1270            View newFocused = findFocusableViewInMyBounds(movingRight,
1271                    mScroller.getFinalX(), findFocus());
1272
1273            if (newFocused == null) {
1274                newFocused = this;
1275            }
1276
1277            if (newFocused != findFocus()
1278                    && newFocused.requestFocus(movingRight ? View.FOCUS_RIGHT : View.FOCUS_LEFT)) {
1279                mScrollViewMovedFocus = true;
1280                mScrollViewMovedFocus = false;
1281            }
1282
1283            invalidate();
1284        }
1285    }
1286
1287    /**
1288     * {@inheritDoc}
1289     *
1290     * <p>This version also clamps the scrolling to the bounds of our child.
1291     */
1292    public void scrollTo(int x, int y) {
1293        // we rely on the fact the View.scrollBy calls scrollTo.
1294        if (getChildCount() > 0) {
1295            View child = getChildAt(0);
1296            x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1297            y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1298            if (x != mScrollX || y != mScrollY) {
1299                super.scrollTo(x, y);
1300            }
1301        }
1302    }
1303
1304    private int clamp(int n, int my, int child) {
1305        if (my >= child || n < 0) {
1306            return 0;
1307        }
1308        if ((my + n) > child) {
1309            return child - my;
1310        }
1311        return n;
1312    }
1313}
1314