2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package android.widget;
19 import android.os.Build;
20 import android.os.Parcel;
21 import android.os.Parcelable;
22 import com.android.internal.R;
24 import android.content.Context;
25 import android.content.res.TypedArray;
26 import android.graphics.Canvas;
27 import android.graphics.Rect;
28 import android.os.Bundle;
29 import android.os.StrictMode;
30 import android.util.AttributeSet;
31 import android.util.Log;
32 import android.view.FocusFinder;
33 import android.view.InputDevice;
34 import android.view.KeyEvent;
35 import android.view.MotionEvent;
36 import android.view.VelocityTracker;
37 import android.view.View;
38 import android.view.ViewConfiguration;
39 import android.view.ViewDebug;
40 import android.view.ViewGroup;
41 import android.view.ViewParent;
42 import android.view.accessibility.AccessibilityEvent;
43 import android.view.accessibility.AccessibilityNodeInfo;
44 import android.view.animation.AnimationUtils;
46 import java.util.List;
49 * Layout container for a view hierarchy that can be scrolled by the user,
50 * allowing it to be larger than the physical display. A ScrollView
51 * is a {@link FrameLayout}, meaning you should place one child in it
52 * containing the entire contents to scroll; this child may itself be a layout
53 * manager with a complex hierarchy of objects. A child that is often used
54 * is a {@link LinearLayout} in a vertical orientation, presenting a vertical
55 * array of top-level items that the user can scroll through.
56 * <p>You should never use a ScrollView with a {@link ListView}, because
57 * ListView takes care of its own vertical scrolling. Most importantly, doing this
58 * defeats all of the important optimizations in ListView for dealing with
59 * large lists, since it effectively forces the ListView to display its entire
60 * list of items to fill up the infinite container supplied by ScrollView.
61 * <p>The {@link TextView} class also
62 * takes care of its own scrolling, so does not require a ScrollView, but
63 * using the two together is possible to achieve the effect of a text view
64 * within a larger container.
66 * <p>ScrollView only supports vertical scrolling. For horizontal scrolling,
67 * use {@link HorizontalScrollView}.
69 * @attr ref android.R.styleable#ScrollView_fillViewport
71 public class ScrollView extends FrameLayout {
72 static final int ANIMATED_SCROLL_GAP = 250;
74 static final float MAX_SCROLL_FACTOR = 0.5f;
76 private static final String TAG = "ScrollView";
78 private long mLastScroll;
80 private final Rect mTempRect = new Rect();
81 private OverScroller mScroller;
82 private EdgeEffect mEdgeGlowTop;
83 private EdgeEffect mEdgeGlowBottom;
86 * Position of the last motion event.
88 private int mLastMotionY;
91 * True when the layout has changed but the traversal has not come through yet.
92 * Ideally the view hierarchy would keep track of this for us.
94 private boolean mIsLayoutDirty = true;
97 * The child to give focus to in the event that a child has requested focus while the
98 * layout is dirty. This prevents the scroll from being wrong if the child has not been
99 * laid out before requesting focus.
101 private View mChildToScrollTo = null;
104 * True if the user is currently dragging this ScrollView around. This is
105 * not the same as 'is being flinged', which can be checked by
106 * mScroller.isFinished() (flinging begins when the user lifts his finger).
108 private boolean mIsBeingDragged = false;
111 * Determines speed during touch scrolling
113 private VelocityTracker mVelocityTracker;
116 * When set to true, the scroll view measure its child to make it fill the currently
119 @ViewDebug.ExportedProperty(category = "layout")
120 private boolean mFillViewport;
123 * Whether arrow scrolling is animated.
125 private boolean mSmoothScrollingEnabled = true;
127 private int mTouchSlop;
128 private int mMinimumVelocity;
129 private int mMaximumVelocity;
131 private int mOverscrollDistance;
132 private int mOverflingDistance;
135 * ID of the active pointer. This is used to retain consistency during
136 * drags/flings if multiple pointers are used.
138 private int mActivePointerId = INVALID_POINTER;
141 * Used during scrolling to retrieve the new offset within the window.
143 private final int[] mScrollOffset = new int[2];
144 private final int[] mScrollConsumed = new int[2];
147 * The StrictMode "critical time span" objects to catch animation
148 * stutters. Non-null when a time-sensitive animation is
149 * in-flight. Must call finish() on them when done animating.
150 * These are no-ops on user builds.
152 private StrictMode.Span mScrollStrictSpan = null; // aka "drag"
153 private StrictMode.Span mFlingStrictSpan = null;
156 * Sentinel value for no current active pointer.
157 * Used by {@link #mActivePointerId}.
159 private static final int INVALID_POINTER = -1;
161 private SavedState mSavedState;
163 public ScrollView(Context context) {
167 public ScrollView(Context context, AttributeSet attrs) {
168 this(context, attrs, com.android.internal.R.attr.scrollViewStyle);
171 public ScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
172 this(context, attrs, defStyleAttr, 0);
175 public ScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
176 super(context, attrs, defStyleAttr, defStyleRes);
179 final TypedArray a = context.obtainStyledAttributes(
180 attrs, com.android.internal.R.styleable.ScrollView, defStyleAttr, defStyleRes);
182 setFillViewport(a.getBoolean(R.styleable.ScrollView_fillViewport, false));
188 public boolean shouldDelayChildPressedState() {
193 protected float getTopFadingEdgeStrength() {
194 if (getChildCount() == 0) {
198 final int length = getVerticalFadingEdgeLength();
199 if (mScrollY < length) {
200 return mScrollY / (float) length;
207 protected float getBottomFadingEdgeStrength() {
208 if (getChildCount() == 0) {
212 final int length = getVerticalFadingEdgeLength();
213 final int bottomEdge = getHeight() - mPaddingBottom;
214 final int span = getChildAt(0).getBottom() - mScrollY - bottomEdge;
216 return span / (float) length;
223 * @return The maximum amount this scroll view will scroll in response to
226 public int getMaxScrollAmount() {
227 return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop));
231 private void initScrollView() {
232 mScroller = new OverScroller(getContext());
234 setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
235 setWillNotDraw(false);
236 final ViewConfiguration configuration = ViewConfiguration.get(mContext);
237 mTouchSlop = configuration.getScaledTouchSlop();
238 mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
239 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
240 mOverscrollDistance = configuration.getScaledOverscrollDistance();
241 mOverflingDistance = configuration.getScaledOverflingDistance();
245 public void addView(View child) {
246 if (getChildCount() > 0) {
247 throw new IllegalStateException("ScrollView can host only one direct child");
250 super.addView(child);
254 public void addView(View child, int index) {
255 if (getChildCount() > 0) {
256 throw new IllegalStateException("ScrollView can host only one direct child");
259 super.addView(child, index);
263 public void addView(View child, ViewGroup.LayoutParams params) {
264 if (getChildCount() > 0) {
265 throw new IllegalStateException("ScrollView can host only one direct child");
268 super.addView(child, params);
272 public void addView(View child, int index, ViewGroup.LayoutParams params) {
273 if (getChildCount() > 0) {
274 throw new IllegalStateException("ScrollView can host only one direct child");
277 super.addView(child, index, params);
281 * @return Returns true this ScrollView can be scrolled
283 private boolean canScroll() {
284 View child = getChildAt(0);
286 int childHeight = child.getHeight();
287 return getHeight() < childHeight + mPaddingTop + mPaddingBottom;
293 * Indicates whether this ScrollView's content is stretched to fill the viewport.
295 * @return True if the content fills the viewport, false otherwise.
297 * @attr ref android.R.styleable#ScrollView_fillViewport
299 public boolean isFillViewport() {
300 return mFillViewport;
304 * Indicates this ScrollView whether it should stretch its content height to fill
305 * the viewport or not.
307 * @param fillViewport True to stretch the content's height to the viewport's
308 * boundaries, false otherwise.
310 * @attr ref android.R.styleable#ScrollView_fillViewport
312 public void setFillViewport(boolean fillViewport) {
313 if (fillViewport != mFillViewport) {
314 mFillViewport = fillViewport;
320 * @return Whether arrow scrolling will animate its transition.
322 public boolean isSmoothScrollingEnabled() {
323 return mSmoothScrollingEnabled;
327 * Set whether arrow scrolling will animate its transition.
328 * @param smoothScrollingEnabled whether arrow scrolling will animate its transition
330 public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) {
331 mSmoothScrollingEnabled = smoothScrollingEnabled;
335 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
336 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
338 if (!mFillViewport) {
342 final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
343 if (heightMode == MeasureSpec.UNSPECIFIED) {
347 if (getChildCount() > 0) {
348 final View child = getChildAt(0);
349 int height = getMeasuredHeight();
350 if (child.getMeasuredHeight() < height) {
351 final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams();
353 int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
354 mPaddingLeft + mPaddingRight, lp.width);
355 height -= mPaddingTop;
356 height -= mPaddingBottom;
357 int childHeightMeasureSpec =
358 MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
360 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
366 public boolean dispatchKeyEvent(KeyEvent event) {
367 // Let the focused view and/or our descendants get the key first
368 return super.dispatchKeyEvent(event) || executeKeyEvent(event);
372 * You can call this function yourself to have the scroll view perform
373 * scrolling from a key event, just as if the event had been dispatched to
374 * it by the view hierarchy.
376 * @param event The key event to execute.
377 * @return Return true if the event was handled, else false.
379 public boolean executeKeyEvent(KeyEvent event) {
380 mTempRect.setEmpty();
383 if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
384 View currentFocused = findFocus();
385 if (currentFocused == this) currentFocused = null;
386 View nextFocused = FocusFinder.getInstance().findNextFocus(this,
387 currentFocused, View.FOCUS_DOWN);
388 return nextFocused != null
389 && nextFocused != this
390 && nextFocused.requestFocus(View.FOCUS_DOWN);
395 boolean handled = false;
396 if (event.getAction() == KeyEvent.ACTION_DOWN) {
397 switch (event.getKeyCode()) {
398 case KeyEvent.KEYCODE_DPAD_UP:
399 if (!event.isAltPressed()) {
400 handled = arrowScroll(View.FOCUS_UP);
402 handled = fullScroll(View.FOCUS_UP);
405 case KeyEvent.KEYCODE_DPAD_DOWN:
406 if (!event.isAltPressed()) {
407 handled = arrowScroll(View.FOCUS_DOWN);
409 handled = fullScroll(View.FOCUS_DOWN);
412 case KeyEvent.KEYCODE_SPACE:
413 pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN);
421 private boolean inChild(int x, int y) {
422 if (getChildCount() > 0) {
423 final int scrollY = mScrollY;
424 final View child = getChildAt(0);
425 return !(y < child.getTop() - scrollY
426 || y >= child.getBottom() - scrollY
427 || x < child.getLeft()
428 || x >= child.getRight());
433 private void initOrResetVelocityTracker() {
434 if (mVelocityTracker == null) {
435 mVelocityTracker = VelocityTracker.obtain();
437 mVelocityTracker.clear();
441 private void initVelocityTrackerIfNotExists() {
442 if (mVelocityTracker == null) {
443 mVelocityTracker = VelocityTracker.obtain();
447 private void recycleVelocityTracker() {
448 if (mVelocityTracker != null) {
449 mVelocityTracker.recycle();
450 mVelocityTracker = null;
455 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
456 if (disallowIntercept) {
457 recycleVelocityTracker();
459 super.requestDisallowInterceptTouchEvent(disallowIntercept);
464 public boolean onInterceptTouchEvent(MotionEvent ev) {
466 * This method JUST determines whether we want to intercept the motion.
467 * If we return true, onMotionEvent will be called and we do the actual
472 * Shortcut the most recurring case: the user is in the dragging
473 * state and he is moving his finger. We want to intercept this
476 final int action = ev.getAction();
477 if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
482 * Don't try to intercept touch if we can't scroll anyway.
484 if (getScrollY() == 0 && !canScrollVertically(1)) {
488 switch (action & MotionEvent.ACTION_MASK) {
489 case MotionEvent.ACTION_MOVE: {
491 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
492 * whether the user has moved far enough from his original down touch.
496 * Locally do absolute value. mLastMotionY is set to the y value
499 final int activePointerId = mActivePointerId;
500 if (activePointerId == INVALID_POINTER) {
501 // If we don't have a valid id, the touch down wasn't on content.
505 final int pointerIndex = ev.findPointerIndex(activePointerId);
506 if (pointerIndex == -1) {
507 Log.e(TAG, "Invalid pointerId=" + activePointerId
508 + " in onInterceptTouchEvent");
512 final int y = (int) ev.getY(pointerIndex);
513 final int yDiff = Math.abs(y - mLastMotionY);
514 if (yDiff > mTouchSlop && (getNestedScrollAxes() & SCROLL_AXIS_VERTICAL) == 0) {
515 mIsBeingDragged = true;
517 initVelocityTrackerIfNotExists();
518 mVelocityTracker.addMovement(ev);
519 if (mScrollStrictSpan == null) {
520 mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll");
522 final ViewParent parent = getParent();
523 if (parent != null) {
524 parent.requestDisallowInterceptTouchEvent(true);
530 case MotionEvent.ACTION_DOWN: {
531 final int y = (int) ev.getY();
532 if (!inChild((int) ev.getX(), (int) y)) {
533 mIsBeingDragged = false;
534 recycleVelocityTracker();
539 * Remember location of down touch.
540 * ACTION_DOWN always refers to pointer index 0.
543 mActivePointerId = ev.getPointerId(0);
545 initOrResetVelocityTracker();
546 mVelocityTracker.addMovement(ev);
548 * If being flinged and user touches the screen, initiate drag;
549 * otherwise don't. mScroller.isFinished should be false when
552 mIsBeingDragged = !mScroller.isFinished();
553 if (mIsBeingDragged && mScrollStrictSpan == null) {
554 mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll");
556 startNestedScroll(SCROLL_AXIS_VERTICAL);
560 case MotionEvent.ACTION_CANCEL:
561 case MotionEvent.ACTION_UP:
562 /* Release the drag */
563 mIsBeingDragged = false;
564 mActivePointerId = INVALID_POINTER;
565 recycleVelocityTracker();
566 if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) {
567 postInvalidateOnAnimation();
571 case MotionEvent.ACTION_POINTER_UP:
572 onSecondaryPointerUp(ev);
577 * The only time we want to intercept motion events is if we are in the
580 return mIsBeingDragged;
584 public boolean onTouchEvent(MotionEvent ev) {
585 initVelocityTrackerIfNotExists();
587 MotionEvent vtev = MotionEvent.obtain(ev);
589 final int action = ev.getAction();
591 switch (action & MotionEvent.ACTION_MASK) {
592 case MotionEvent.ACTION_DOWN: {
593 if (getChildCount() == 0) {
596 if ((mIsBeingDragged = !mScroller.isFinished())) {
597 final ViewParent parent = getParent();
598 if (parent != null) {
599 parent.requestDisallowInterceptTouchEvent(true);
604 * If being flinged and user touches, stop the fling. isFinished
605 * will be false if being flinged.
607 if (!mScroller.isFinished()) {
608 mScroller.abortAnimation();
609 if (mFlingStrictSpan != null) {
610 mFlingStrictSpan.finish();
611 mFlingStrictSpan = null;
615 // Remember where the motion event started
616 mLastMotionY = (int) ev.getY();
617 mActivePointerId = ev.getPointerId(0);
618 startNestedScroll(SCROLL_AXIS_VERTICAL);
621 case MotionEvent.ACTION_MOVE:
622 final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
623 if (activePointerIndex == -1) {
624 Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
628 final int y = (int) ev.getY(activePointerIndex);
629 int deltaY = mLastMotionY - y;
630 if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) {
631 deltaY -= mScrollConsumed[1];
632 vtev.offsetLocation(0, mScrollOffset[1]);
634 if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) {
635 final ViewParent parent = getParent();
636 if (parent != null) {
637 parent.requestDisallowInterceptTouchEvent(true);
639 mIsBeingDragged = true;
641 deltaY -= mTouchSlop;
643 deltaY += mTouchSlop;
646 if (mIsBeingDragged) {
647 // Scroll to follow the motion event
648 mLastMotionY = y - mScrollOffset[1];
650 final int oldY = mScrollY;
651 final int range = getScrollRange();
652 final int overscrollMode = getOverScrollMode();
653 boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS ||
654 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0);
656 // Calling overScrollBy will call onOverScrolled, which
657 // calls onScrollChanged if applicable.
658 if (overScrollBy(0, deltaY, 0, mScrollY, 0, range, 0, mOverscrollDistance, true)
659 && !hasNestedScrollingParent()) {
660 // Break our velocity if we hit a scroll barrier.
661 mVelocityTracker.clear();
664 final int scrolledDeltaY = mScrollY - oldY;
665 final int unconsumedY = deltaY - scrolledDeltaY;
666 if (dispatchNestedScroll(0, scrolledDeltaY, 0, unconsumedY, mScrollOffset)) {
667 mLastMotionY -= mScrollOffset[1];
668 vtev.offsetLocation(0, mScrollOffset[1]);
669 } else if (canOverscroll) {
670 final int pulledToY = oldY + deltaY;
672 mEdgeGlowTop.onPull((float) deltaY / getHeight(),
673 ev.getX(activePointerIndex) / getWidth());
674 if (!mEdgeGlowBottom.isFinished()) {
675 mEdgeGlowBottom.onRelease();
677 } else if (pulledToY > range) {
678 mEdgeGlowBottom.onPull((float) deltaY / getHeight(),
679 1.f - ev.getX(activePointerIndex) / getWidth());
680 if (!mEdgeGlowTop.isFinished()) {
681 mEdgeGlowTop.onRelease();
684 if (mEdgeGlowTop != null
685 && (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) {
686 postInvalidateOnAnimation();
691 case MotionEvent.ACTION_UP:
692 if (mIsBeingDragged) {
693 final VelocityTracker velocityTracker = mVelocityTracker;
694 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
695 int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
697 if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
698 flingWithNestedDispatch(-initialVelocity);
699 } else if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0,
701 postInvalidateOnAnimation();
704 mActivePointerId = INVALID_POINTER;
708 case MotionEvent.ACTION_CANCEL:
709 if (mIsBeingDragged && getChildCount() > 0) {
710 if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) {
711 postInvalidateOnAnimation();
713 mActivePointerId = INVALID_POINTER;
717 case MotionEvent.ACTION_POINTER_DOWN: {
718 final int index = ev.getActionIndex();
719 mLastMotionY = (int) ev.getY(index);
720 mActivePointerId = ev.getPointerId(index);
723 case MotionEvent.ACTION_POINTER_UP:
724 onSecondaryPointerUp(ev);
725 mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId));
729 if (mVelocityTracker != null) {
730 mVelocityTracker.addMovement(vtev);
736 private void onSecondaryPointerUp(MotionEvent ev) {
737 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
738 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
739 final int pointerId = ev.getPointerId(pointerIndex);
740 if (pointerId == mActivePointerId) {
741 // This was our active pointer going up. Choose a new
742 // active pointer and adjust accordingly.
743 // TODO: Make this decision more intelligent.
744 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
745 mLastMotionY = (int) ev.getY(newPointerIndex);
746 mActivePointerId = ev.getPointerId(newPointerIndex);
747 if (mVelocityTracker != null) {
748 mVelocityTracker.clear();
754 public boolean onGenericMotionEvent(MotionEvent event) {
755 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
756 switch (event.getAction()) {
757 case MotionEvent.ACTION_SCROLL: {
758 if (!mIsBeingDragged) {
759 final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
761 final int delta = (int) (vscroll * getVerticalScrollFactor());
762 final int range = getScrollRange();
763 int oldScrollY = mScrollY;
764 int newScrollY = oldScrollY - delta;
765 if (newScrollY < 0) {
767 } else if (newScrollY > range) {
770 if (newScrollY != oldScrollY) {
771 super.scrollTo(mScrollX, newScrollY);
779 return super.onGenericMotionEvent(event);
783 protected void onOverScrolled(int scrollX, int scrollY,
784 boolean clampedX, boolean clampedY) {
785 // Treat animating scrolls differently; see #computeScroll() for why.
786 if (!mScroller.isFinished()) {
787 final int oldX = mScrollX;
788 final int oldY = mScrollY;
791 invalidateParentIfNeeded();
792 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
794 mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange());
797 super.scrollTo(scrollX, scrollY);
804 public boolean performAccessibilityAction(int action, Bundle arguments) {
805 if (super.performAccessibilityAction(action, arguments)) {
812 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
813 final int viewportHeight = getHeight() - mPaddingBottom - mPaddingTop;
814 final int targetScrollY = Math.min(mScrollY + viewportHeight, getScrollRange());
815 if (targetScrollY != mScrollY) {
816 smoothScrollTo(0, targetScrollY);
820 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
821 final int viewportHeight = getHeight() - mPaddingBottom - mPaddingTop;
822 final int targetScrollY = Math.max(mScrollY - viewportHeight, 0);
823 if (targetScrollY != mScrollY) {
824 smoothScrollTo(0, targetScrollY);
833 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
834 super.onInitializeAccessibilityNodeInfo(info);
835 info.setClassName(ScrollView.class.getName());
837 final int scrollRange = getScrollRange();
838 if (scrollRange > 0) {
839 info.setScrollable(true);
841 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
843 if (mScrollY < scrollRange) {
844 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
851 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
852 super.onInitializeAccessibilityEvent(event);
853 event.setClassName(ScrollView.class.getName());
854 final boolean scrollable = getScrollRange() > 0;
855 event.setScrollable(scrollable);
856 event.setScrollX(mScrollX);
857 event.setScrollY(mScrollY);
858 event.setMaxScrollX(mScrollX);
859 event.setMaxScrollY(getScrollRange());
862 private int getScrollRange() {
864 if (getChildCount() > 0) {
865 View child = getChildAt(0);
866 scrollRange = Math.max(0,
867 child.getHeight() - (getHeight() - mPaddingBottom - mPaddingTop));
874 * Finds the next focusable component that fits in the specified bounds.
877 * @param topFocus look for a candidate is the one at the top of the bounds
878 * if topFocus is true, or at the bottom of the bounds if topFocus is
880 * @param top the top offset of the bounds in which a focusable must be
882 * @param bottom the bottom offset of the bounds in which a focusable must
884 * @return the next focusable component in the bounds or null if none can
887 private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) {
889 List<View> focusables = getFocusables(View.FOCUS_FORWARD);
890 View focusCandidate = null;
893 * A fully contained focusable is one where its top is below the bound's
894 * top, and its bottom is above the bound's bottom. A partially
895 * contained focusable is one where some part of it is within the
896 * bounds, but it also has some part that is not within bounds. A fully contained
897 * focusable is preferred to a partially contained focusable.
899 boolean foundFullyContainedFocusable = false;
901 int count = focusables.size();
902 for (int i = 0; i < count; i++) {
903 View view = focusables.get(i);
904 int viewTop = view.getTop();
905 int viewBottom = view.getBottom();
907 if (top < viewBottom && viewTop < bottom) {
909 * the focusable is in the target area, it is a candidate for
913 final boolean viewIsFullyContained = (top < viewTop) &&
914 (viewBottom < bottom);
916 if (focusCandidate == null) {
917 /* No candidate, take this one */
918 focusCandidate = view;
919 foundFullyContainedFocusable = viewIsFullyContained;
921 final boolean viewIsCloserToBoundary =
922 (topFocus && viewTop < focusCandidate.getTop()) ||
923 (!topFocus && viewBottom > focusCandidate
926 if (foundFullyContainedFocusable) {
927 if (viewIsFullyContained && viewIsCloserToBoundary) {
929 * We're dealing with only fully contained views, so
930 * it has to be closer to the boundary to beat our
933 focusCandidate = view;
936 if (viewIsFullyContained) {
937 /* Any fully contained view beats a partially contained view */
938 focusCandidate = view;
939 foundFullyContainedFocusable = true;
940 } else if (viewIsCloserToBoundary) {
942 * Partially contained view beats another partially
943 * contained view if it's closer
945 focusCandidate = view;
952 return focusCandidate;
956 * <p>Handles scrolling in response to a "page up/down" shortcut press. This
957 * method will scroll the view by one page up or down and give the focus
958 * to the topmost/bottommost component in the new visible area. If no
959 * component is a good candidate for focus, this scrollview reclaims the
962 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
963 * to go one page up or
964 * {@link android.view.View#FOCUS_DOWN} to go one page down
965 * @return true if the key event is consumed by this method, false otherwise
967 public boolean pageScroll(int direction) {
968 boolean down = direction == View.FOCUS_DOWN;
969 int height = getHeight();
972 mTempRect.top = getScrollY() + height;
973 int count = getChildCount();
975 View view = getChildAt(count - 1);
976 if (mTempRect.top + height > view.getBottom()) {
977 mTempRect.top = view.getBottom() - height;
981 mTempRect.top = getScrollY() - height;
982 if (mTempRect.top < 0) {
986 mTempRect.bottom = mTempRect.top + height;
988 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
992 * <p>Handles scrolling in response to a "home/end" shortcut press. This
993 * method will scroll the view to the top or bottom and give the focus
994 * to the topmost/bottommost component in the new visible area. If no
995 * component is a good candidate for focus, this scrollview reclaims the
998 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
999 * to go the top of the view or
1000 * {@link android.view.View#FOCUS_DOWN} to go the bottom
1001 * @return true if the key event is consumed by this method, false otherwise
1003 public boolean fullScroll(int direction) {
1004 boolean down = direction == View.FOCUS_DOWN;
1005 int height = getHeight();
1008 mTempRect.bottom = height;
1011 int count = getChildCount();
1013 View view = getChildAt(count - 1);
1014 mTempRect.bottom = view.getBottom() + mPaddingBottom;
1015 mTempRect.top = mTempRect.bottom - height;
1019 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
1023 * <p>Scrolls the view to make the area defined by <code>top</code> and
1024 * <code>bottom</code> visible. This method attempts to give the focus
1025 * to a component visible in this area. If no component can be focused in
1026 * the new visible area, the focus is reclaimed by this ScrollView.</p>
1028 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
1029 * to go upward, {@link android.view.View#FOCUS_DOWN} to downward
1030 * @param top the top offset of the new area to be made visible
1031 * @param bottom the bottom offset of the new area to be made visible
1032 * @return true if the key event is consumed by this method, false otherwise
1034 private boolean scrollAndFocus(int direction, int top, int bottom) {
1035 boolean handled = true;
1037 int height = getHeight();
1038 int containerTop = getScrollY();
1039 int containerBottom = containerTop + height;
1040 boolean up = direction == View.FOCUS_UP;
1042 View newFocused = findFocusableViewInBounds(up, top, bottom);
1043 if (newFocused == null) {
1047 if (top >= containerTop && bottom <= containerBottom) {
1050 int delta = up ? (top - containerTop) : (bottom - containerBottom);
1054 if (newFocused != findFocus()) newFocused.requestFocus(direction);
1060 * Handle scrolling in response to an up or down arrow click.
1062 * @param direction The direction corresponding to the arrow key that was
1064 * @return True if we consumed the event, false otherwise
1066 public boolean arrowScroll(int direction) {
1068 View currentFocused = findFocus();
1069 if (currentFocused == this) currentFocused = null;
1071 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
1073 final int maxJump = getMaxScrollAmount();
1075 if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) {
1076 nextFocused.getDrawingRect(mTempRect);
1077 offsetDescendantRectToMyCoords(nextFocused, mTempRect);
1078 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1079 doScrollY(scrollDelta);
1080 nextFocused.requestFocus(direction);
1083 int scrollDelta = maxJump;
1085 if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
1086 scrollDelta = getScrollY();
1087 } else if (direction == View.FOCUS_DOWN) {
1088 if (getChildCount() > 0) {
1089 int daBottom = getChildAt(0).getBottom();
1090 int screenBottom = getScrollY() + getHeight() - mPaddingBottom;
1091 if (daBottom - screenBottom < maxJump) {
1092 scrollDelta = daBottom - screenBottom;
1096 if (scrollDelta == 0) {
1099 doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta);
1102 if (currentFocused != null && currentFocused.isFocused()
1103 && isOffScreen(currentFocused)) {
1104 // previously focused item still has focus and is off screen, give
1105 // it up (take it back to ourselves)
1106 // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
1109 final int descendantFocusability = getDescendantFocusability(); // save
1110 setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
1112 setDescendantFocusability(descendantFocusability); // restore
1118 * @return whether the descendant of this scroll view is scrolled off
1121 private boolean isOffScreen(View descendant) {
1122 return !isWithinDeltaOfScreen(descendant, 0, getHeight());
1126 * @return whether the descendant of this scroll view is within delta
1127 * pixels of being on the screen.
1129 private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) {
1130 descendant.getDrawingRect(mTempRect);
1131 offsetDescendantRectToMyCoords(descendant, mTempRect);
1133 return (mTempRect.bottom + delta) >= getScrollY()
1134 && (mTempRect.top - delta) <= (getScrollY() + height);
1138 * Smooth scroll by a Y delta
1140 * @param delta the number of pixels to scroll by on the Y axis
1142 private void doScrollY(int delta) {
1144 if (mSmoothScrollingEnabled) {
1145 smoothScrollBy(0, delta);
1153 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
1155 * @param dx the number of pixels to scroll by on the X axis
1156 * @param dy the number of pixels to scroll by on the Y axis
1158 public final void smoothScrollBy(int dx, int dy) {
1159 if (getChildCount() == 0) {
1163 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
1164 if (duration > ANIMATED_SCROLL_GAP) {
1165 final int height = getHeight() - mPaddingBottom - mPaddingTop;
1166 final int bottom = getChildAt(0).getHeight();
1167 final int maxY = Math.max(0, bottom - height);
1168 final int scrollY = mScrollY;
1169 dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
1171 mScroller.startScroll(mScrollX, scrollY, 0, dy);
1172 postInvalidateOnAnimation();
1174 if (!mScroller.isFinished()) {
1175 mScroller.abortAnimation();
1176 if (mFlingStrictSpan != null) {
1177 mFlingStrictSpan.finish();
1178 mFlingStrictSpan = null;
1183 mLastScroll = AnimationUtils.currentAnimationTimeMillis();
1187 * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
1189 * @param x the position where to scroll on the X axis
1190 * @param y the position where to scroll on the Y axis
1192 public final void smoothScrollTo(int x, int y) {
1193 smoothScrollBy(x - mScrollX, y - mScrollY);
1197 * <p>The scroll range of a scroll view is the overall height of all of its
1201 protected int computeVerticalScrollRange() {
1202 final int count = getChildCount();
1203 final int contentHeight = getHeight() - mPaddingBottom - mPaddingTop;
1205 return contentHeight;
1208 int scrollRange = getChildAt(0).getBottom();
1209 final int scrollY = mScrollY;
1210 final int overscrollBottom = Math.max(0, scrollRange - contentHeight);
1212 scrollRange -= scrollY;
1213 } else if (scrollY > overscrollBottom) {
1214 scrollRange += scrollY - overscrollBottom;
1221 protected int computeVerticalScrollOffset() {
1222 return Math.max(0, super.computeVerticalScrollOffset());
1226 protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
1227 ViewGroup.LayoutParams lp = child.getLayoutParams();
1229 int childWidthMeasureSpec;
1230 int childHeightMeasureSpec;
1232 childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft
1233 + mPaddingRight, lp.width);
1235 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1237 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1241 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
1242 int parentHeightMeasureSpec, int heightUsed) {
1243 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
1245 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
1246 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
1247 + widthUsed, lp.width);
1248 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
1249 lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);
1251 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1255 public void computeScroll() {
1256 if (mScroller.computeScrollOffset()) {
1257 // This is called at drawing time by ViewGroup. We don't want to
1258 // re-show the scrollbars at this point, which scrollTo will do,
1259 // so we replicate most of scrollTo here.
1261 // It's a little odd to call onScrollChanged from inside the drawing.
1263 // It is, except when you remember that computeScroll() is used to
1264 // animate scrolling. So unless we want to defer the onScrollChanged()
1265 // until the end of the animated scrolling, we don't really have a
1268 // I agree. The alternative, which I think would be worse, is to post
1269 // something and tell the subclasses later. This is bad because there
1270 // will be a window where mScrollX/Y is different from what the app
1273 int oldX = mScrollX;
1274 int oldY = mScrollY;
1275 int x = mScroller.getCurrX();
1276 int y = mScroller.getCurrY();
1278 if (oldX != x || oldY != y) {
1279 final int range = getScrollRange();
1280 final int overscrollMode = getOverScrollMode();
1281 final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS ||
1282 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0);
1284 overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, range,
1285 0, mOverflingDistance, false);
1286 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
1288 if (canOverscroll) {
1289 if (y < 0 && oldY >= 0) {
1290 mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity());
1291 } else if (y > range && oldY <= range) {
1292 mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity());
1297 if (!awakenScrollBars()) {
1298 // Keep on drawing until the animation has finished.
1299 postInvalidateOnAnimation();
1302 if (mFlingStrictSpan != null) {
1303 mFlingStrictSpan.finish();
1304 mFlingStrictSpan = null;
1310 * Scrolls the view to the given child.
1312 * @param child the View to scroll to
1314 private void scrollToChild(View child) {
1315 child.getDrawingRect(mTempRect);
1317 /* Offset from child's local coordinates to ScrollView coordinates */
1318 offsetDescendantRectToMyCoords(child, mTempRect);
1320 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1322 if (scrollDelta != 0) {
1323 scrollBy(0, scrollDelta);
1328 * If rect is off screen, scroll just enough to get it (or at least the
1329 * first screen size chunk of it) on screen.
1331 * @param rect The rectangle.
1332 * @param immediate True to scroll immediately without animation
1333 * @return true if scrolling was performed
1335 private boolean scrollToChildRect(Rect rect, boolean immediate) {
1336 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
1337 final boolean scroll = delta != 0;
1342 smoothScrollBy(0, delta);
1349 * Compute the amount to scroll in the Y direction in order to get
1350 * a rectangle completely on the screen (or, if taller than the screen,
1351 * at least the first screen size chunk of it).
1353 * @param rect The rect.
1354 * @return The scroll delta.
1356 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
1357 if (getChildCount() == 0) return 0;
1359 int height = getHeight();
1360 int screenTop = getScrollY();
1361 int screenBottom = screenTop + height;
1363 int fadingEdge = getVerticalFadingEdgeLength();
1365 // leave room for top fading edge as long as rect isn't at very top
1367 screenTop += fadingEdge;
1370 // leave room for bottom fading edge as long as rect isn't at very bottom
1371 if (rect.bottom < getChildAt(0).getHeight()) {
1372 screenBottom -= fadingEdge;
1375 int scrollYDelta = 0;
1377 if (rect.bottom > screenBottom && rect.top > screenTop) {
1378 // need to move down to get it in view: move down just enough so
1379 // that the entire rectangle is in view (or at least the first
1380 // screen size chunk).
1382 if (rect.height() > height) {
1383 // just enough to get screen size chunk on
1384 scrollYDelta += (rect.top - screenTop);
1386 // get entire rect at bottom of screen
1387 scrollYDelta += (rect.bottom - screenBottom);
1390 // make sure we aren't scrolling beyond the end of our content
1391 int bottom = getChildAt(0).getBottom();
1392 int distanceToBottom = bottom - screenBottom;
1393 scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
1395 } else if (rect.top < screenTop && rect.bottom < screenBottom) {
1396 // need to move up to get it in view: move up just enough so that
1397 // entire rectangle is in view (or at least the first screen
1398 // size chunk of it).
1400 if (rect.height() > height) {
1401 // screen size chunk
1402 scrollYDelta -= (screenBottom - rect.bottom);
1404 // entire rect at top
1405 scrollYDelta -= (screenTop - rect.top);
1408 // make sure we aren't scrolling any further than the top our content
1409 scrollYDelta = Math.max(scrollYDelta, -getScrollY());
1411 return scrollYDelta;
1415 public void requestChildFocus(View child, View focused) {
1416 if (!mIsLayoutDirty) {
1417 scrollToChild(focused);
1419 // The child may not be laid out yet, we can't compute the scroll yet
1420 mChildToScrollTo = focused;
1422 super.requestChildFocus(child, focused);
1427 * When looking for focus in children of a scroll view, need to be a little
1428 * more careful not to give focus to something that is scrolled off screen.
1430 * This is more expensive than the default {@link android.view.ViewGroup}
1431 * implementation, otherwise this behavior might have been made the default.
1434 protected boolean onRequestFocusInDescendants(int direction,
1435 Rect previouslyFocusedRect) {
1437 // convert from forward / backward notation to up / down / left / right
1439 if (direction == View.FOCUS_FORWARD) {
1440 direction = View.FOCUS_DOWN;
1441 } else if (direction == View.FOCUS_BACKWARD) {
1442 direction = View.FOCUS_UP;
1445 final View nextFocus = previouslyFocusedRect == null ?
1446 FocusFinder.getInstance().findNextFocus(this, null, direction) :
1447 FocusFinder.getInstance().findNextFocusFromRect(this,
1448 previouslyFocusedRect, direction);
1450 if (nextFocus == null) {
1454 if (isOffScreen(nextFocus)) {
1458 return nextFocus.requestFocus(direction, previouslyFocusedRect);
1462 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1463 boolean immediate) {
1464 // offset into coordinate space of this scroll view
1465 rectangle.offset(child.getLeft() - child.getScrollX(),
1466 child.getTop() - child.getScrollY());
1468 return scrollToChildRect(rectangle, immediate);
1472 public void requestLayout() {
1473 mIsLayoutDirty = true;
1474 super.requestLayout();
1478 protected void onDetachedFromWindow() {
1479 super.onDetachedFromWindow();
1481 if (mScrollStrictSpan != null) {
1482 mScrollStrictSpan.finish();
1483 mScrollStrictSpan = null;
1485 if (mFlingStrictSpan != null) {
1486 mFlingStrictSpan.finish();
1487 mFlingStrictSpan = null;
1492 protected void onLayout(boolean changed, int l, int t, int r, int b) {
1493 super.onLayout(changed, l, t, r, b);
1494 mIsLayoutDirty = false;
1495 // Give a child focus if it needs it
1496 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1497 scrollToChild(mChildToScrollTo);
1499 mChildToScrollTo = null;
1502 if (mSavedState != null) {
1503 mScrollY = mSavedState.scrollPosition;
1505 } // mScrollY default value is "0"
1507 final int childHeight = (getChildCount() > 0) ? getChildAt(0).getMeasuredHeight() : 0;
1508 final int scrollRange = Math.max(0,
1509 childHeight - (b - t - mPaddingBottom - mPaddingTop));
1511 // Don't forget to clamp
1512 if (mScrollY > scrollRange) {
1513 mScrollY = scrollRange;
1514 } else if (mScrollY < 0) {
1519 // Calling this with the present values causes it to re-claim them
1520 scrollTo(mScrollX, mScrollY);
1524 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1525 super.onSizeChanged(w, h, oldw, oldh);
1527 View currentFocused = findFocus();
1528 if (null == currentFocused || this == currentFocused)
1531 // If the currently-focused view was visible on the screen when the
1532 // screen was at the old height, then scroll the screen to make that
1533 // view visible with the new screen height.
1534 if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) {
1535 currentFocused.getDrawingRect(mTempRect);
1536 offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1537 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1538 doScrollY(scrollDelta);
1543 * Return true if child is a descendant of parent, (or equal to the parent).
1545 private static boolean isViewDescendantOf(View child, View parent) {
1546 if (child == parent) {
1550 final ViewParent theParent = child.getParent();
1551 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1555 * Fling the scroll view
1557 * @param velocityY The initial velocity in the Y direction. Positive
1558 * numbers mean that the finger/cursor is moving down the screen,
1559 * which means we want to scroll towards the top.
1561 public void fling(int velocityY) {
1562 if (getChildCount() > 0) {
1563 int height = getHeight() - mPaddingBottom - mPaddingTop;
1564 int bottom = getChildAt(0).getHeight();
1566 mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0,
1567 Math.max(0, bottom - height), 0, height/2);
1569 if (mFlingStrictSpan == null) {
1570 mFlingStrictSpan = StrictMode.enterCriticalSpan("ScrollView-fling");
1573 postInvalidateOnAnimation();
1577 private void flingWithNestedDispatch(int velocityY) {
1578 final boolean canFling = (mScrollY > 0 || velocityY > 0) &&
1579 (mScrollY < getScrollRange() || velocityY < 0);
1580 if (!dispatchNestedPreFling(0, velocityY)) {
1581 dispatchNestedFling(0, velocityY, canFling);
1588 private void endDrag() {
1589 mIsBeingDragged = false;
1591 recycleVelocityTracker();
1593 if (mEdgeGlowTop != null) {
1594 mEdgeGlowTop.onRelease();
1595 mEdgeGlowBottom.onRelease();
1598 if (mScrollStrictSpan != null) {
1599 mScrollStrictSpan.finish();
1600 mScrollStrictSpan = null;
1607 * <p>This version also clamps the scrolling to the bounds of our child.
1610 public void scrollTo(int x, int y) {
1611 // we rely on the fact the View.scrollBy calls scrollTo.
1612 if (getChildCount() > 0) {
1613 View child = getChildAt(0);
1614 x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1615 y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1616 if (x != mScrollX || y != mScrollY) {
1617 super.scrollTo(x, y);
1623 public void setOverScrollMode(int mode) {
1624 if (mode != OVER_SCROLL_NEVER) {
1625 if (mEdgeGlowTop == null) {
1626 Context context = getContext();
1627 mEdgeGlowTop = new EdgeEffect(context);
1628 mEdgeGlowBottom = new EdgeEffect(context);
1631 mEdgeGlowTop = null;
1632 mEdgeGlowBottom = null;
1634 super.setOverScrollMode(mode);
1638 public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
1639 return (nestedScrollAxes & SCROLL_AXIS_VERTICAL) != 0;
1643 public void onNestedScrollAccepted(View child, View target, int axes) {
1644 super.onNestedScrollAccepted(child, target, axes);
1645 startNestedScroll(SCROLL_AXIS_VERTICAL);
1652 public void onStopNestedScroll(View target) {
1653 super.onStopNestedScroll(target);
1657 public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
1658 int dxUnconsumed, int dyUnconsumed) {
1659 final int oldScrollY = mScrollY;
1660 scrollBy(0, dyUnconsumed);
1661 final int myConsumed = mScrollY - oldScrollY;
1662 final int myUnconsumed = dyUnconsumed - myConsumed;
1663 dispatchNestedScroll(0, myConsumed, 0, myUnconsumed, null);
1670 public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
1672 flingWithNestedDispatch((int) velocityY);
1679 public void draw(Canvas canvas) {
1681 if (mEdgeGlowTop != null) {
1682 final int scrollY = mScrollY;
1683 if (!mEdgeGlowTop.isFinished()) {
1684 final int restoreCount = canvas.save();
1685 final int width = getWidth() - mPaddingLeft - mPaddingRight;
1687 canvas.translate(mPaddingLeft, Math.min(0, scrollY));
1688 mEdgeGlowTop.setSize(width, getHeight());
1689 if (mEdgeGlowTop.draw(canvas)) {
1690 postInvalidateOnAnimation();
1692 canvas.restoreToCount(restoreCount);
1694 if (!mEdgeGlowBottom.isFinished()) {
1695 final int restoreCount = canvas.save();
1696 final int width = getWidth() - mPaddingLeft - mPaddingRight;
1697 final int height = getHeight();
1699 canvas.translate(-width + mPaddingLeft,
1700 Math.max(getScrollRange(), scrollY) + height);
1701 canvas.rotate(180, width, 0);
1702 mEdgeGlowBottom.setSize(width, height);
1703 if (mEdgeGlowBottom.draw(canvas)) {
1704 postInvalidateOnAnimation();
1706 canvas.restoreToCount(restoreCount);
1711 private static int clamp(int n, int my, int child) {
1712 if (my >= child || n < 0) {
1713 /* my >= child is this case:
1714 * |--------------- me ---------------|
1715 * |------ child ------|
1717 * |--------------- me ---------------|
1718 * |------ child ------|
1720 * |--------------- me ---------------|
1721 * |------ child ------|
1723 * n < 0 is this case:
1724 * |------ me ------|
1725 * |-------- child --------|
1730 if ((my+n) > child) {
1732 * |------ me ------|
1733 * |------ child ------|
1742 protected void onRestoreInstanceState(Parcelable state) {
1743 if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1744 // Some old apps reused IDs in ways they shouldn't have.
1745 // Don't break them, but they don't get scroll state restoration.
1746 super.onRestoreInstanceState(state);
1749 SavedState ss = (SavedState) state;
1750 super.onRestoreInstanceState(ss.getSuperState());
1756 protected Parcelable onSaveInstanceState() {
1757 if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1758 // Some old apps reused IDs in ways they shouldn't have.
1759 // Don't break them, but they don't get scroll state restoration.
1760 return super.onSaveInstanceState();
1762 Parcelable superState = super.onSaveInstanceState();
1763 SavedState ss = new SavedState(superState);
1764 ss.scrollPosition = mScrollY;
1768 static class SavedState extends BaseSavedState {
1769 public int scrollPosition;
1771 SavedState(Parcelable superState) {
1775 public SavedState(Parcel source) {
1777 scrollPosition = source.readInt();
1781 public void writeToParcel(Parcel dest, int flags) {
1782 super.writeToParcel(dest, flags);
1783 dest.writeInt(scrollPosition);
1787 public String toString() {
1788 return "HorizontalScrollView.SavedState{"
1789 + Integer.toHexString(System.identityHashCode(this))
1790 + " scrollPosition=" + scrollPosition + "}";
1793 public static final Parcelable.Creator<SavedState> CREATOR
1794 = new Parcelable.Creator<SavedState>() {
1795 public SavedState createFromParcel(Parcel in) {
1796 return new SavedState(in);
1799 public SavedState[] newArray(int size) {
1800 return new SavedState[size];