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