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