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