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