1 /* 2 * Copyright (C) 2006 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.annotation.ColorInt; 20 import android.annotation.NonNull; 21 import android.compat.annotation.UnsupportedAppUsage; 22 import android.content.Context; 23 import android.content.res.Configuration; 24 import android.content.res.TypedArray; 25 import android.graphics.Canvas; 26 import android.graphics.Rect; 27 import android.os.Build; 28 import android.os.Build.VERSION_CODES; 29 import android.os.Bundle; 30 import android.os.Parcel; 31 import android.os.Parcelable; 32 import android.os.StrictMode; 33 import android.util.AttributeSet; 34 import android.util.Log; 35 import android.view.FocusFinder; 36 import android.view.InputDevice; 37 import android.view.KeyEvent; 38 import android.view.MotionEvent; 39 import android.view.VelocityTracker; 40 import android.view.View; 41 import android.view.ViewConfiguration; 42 import android.view.ViewDebug; 43 import android.view.ViewGroup; 44 import android.view.ViewHierarchyEncoder; 45 import android.view.ViewParent; 46 import android.view.accessibility.AccessibilityEvent; 47 import android.view.accessibility.AccessibilityNodeInfo; 48 import android.view.animation.AnimationUtils; 49 import android.view.inspector.InspectableProperty; 50 51 import com.android.internal.R; 52 53 import java.util.List; 54 55 /** 56 * A view group that allows the view hierarchy placed within it to be scrolled. 57 * Scroll view may have only one direct child placed within it. 58 * To add multiple views within the scroll view, make 59 * the direct child you add a view group, for example {@link LinearLayout}, and 60 * place additional views within that LinearLayout. 61 * 62 * <p>Scroll view supports vertical scrolling only. For horizontal scrolling, 63 * use {@link HorizontalScrollView} instead.</p> 64 * 65 * <p>Never add a {@link android.support.v7.widget.RecyclerView} or {@link ListView} to 66 * a scroll view. Doing so results in poor user interface performance and a poor user 67 * experience.</p> 68 * 69 * <p class="note"> 70 * For vertical scrolling, consider {@link android.support.v4.widget.NestedScrollView} 71 * instead of scroll view which offers greater user interface flexibility and 72 * support for the material design scrolling patterns.</p> 73 * 74 * <p>Material Design offers guidelines on how the appearance of 75 * <a href="https://material.io/components/">several UI components</a>, including app bars and 76 * banners, should respond to gestures.</p> 77 * 78 * @attr ref android.R.styleable#ScrollView_fillViewport 79 */ 80 public class ScrollView extends FrameLayout { 81 static final int ANIMATED_SCROLL_GAP = 250; 82 83 static final float MAX_SCROLL_FACTOR = 0.5f; 84 85 private static final String TAG = "ScrollView"; 86 87 @UnsupportedAppUsage 88 private long mLastScroll; 89 90 private final Rect mTempRect = new Rect(); 91 @UnsupportedAppUsage 92 private OverScroller mScroller; 93 /** 94 * Tracks the state of the top edge glow. 95 * 96 * Even though this field is practically final, we cannot make it final because there are apps 97 * setting it via reflection and they need to keep working until they target Q. 98 */ 99 @NonNull 100 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123768600) 101 private EdgeEffect mEdgeGlowTop = new EdgeEffect(getContext()); 102 103 /** 104 * Tracks the state of the bottom edge glow. 105 * 106 * Even though this field is practically final, we cannot make it final because there are apps 107 * setting it via reflection and they need to keep working until they target Q. 108 */ 109 @NonNull 110 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769386) 111 private EdgeEffect mEdgeGlowBottom = new EdgeEffect(getContext()); 112 113 /** 114 * Position of the last motion event. 115 */ 116 @UnsupportedAppUsage 117 private int mLastMotionY; 118 119 /** 120 * True when the layout has changed but the traversal has not come through yet. 121 * Ideally the view hierarchy would keep track of this for us. 122 */ 123 private boolean mIsLayoutDirty = true; 124 125 /** 126 * The child to give focus to in the event that a child has requested focus while the 127 * layout is dirty. This prevents the scroll from being wrong if the child has not been 128 * laid out before requesting focus. 129 */ 130 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769715) 131 private View mChildToScrollTo = null; 132 133 /** 134 * True if the user is currently dragging this ScrollView around. This is 135 * not the same as 'is being flinged', which can be checked by 136 * mScroller.isFinished() (flinging begins when the user lifts his finger). 137 */ 138 @UnsupportedAppUsage 139 private boolean mIsBeingDragged = false; 140 141 /** 142 * Determines speed during touch scrolling 143 */ 144 @UnsupportedAppUsage 145 private VelocityTracker mVelocityTracker; 146 147 /** 148 * When set to true, the scroll view measure its child to make it fill the currently 149 * visible area. 150 */ 151 @ViewDebug.ExportedProperty(category = "layout") 152 private boolean mFillViewport; 153 154 /** 155 * Whether arrow scrolling is animated. 156 */ 157 private boolean mSmoothScrollingEnabled = true; 158 159 private int mTouchSlop; 160 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124051125) 161 private int mMinimumVelocity; 162 private int mMaximumVelocity; 163 164 @UnsupportedAppUsage(maxTargetSdk = VERSION_CODES.P, trackingBug = 124050903) 165 private int mOverscrollDistance; 166 @UnsupportedAppUsage(maxTargetSdk = VERSION_CODES.P, trackingBug = 124050903) 167 private int mOverflingDistance; 168 169 private float mVerticalScrollFactor; 170 171 /** 172 * ID of the active pointer. This is used to retain consistency during 173 * drags/flings if multiple pointers are used. 174 */ 175 private int mActivePointerId = INVALID_POINTER; 176 177 /** 178 * Used during scrolling to retrieve the new offset within the window. 179 */ 180 private final int[] mScrollOffset = new int[2]; 181 private final int[] mScrollConsumed = new int[2]; 182 private int mNestedYOffset; 183 184 /** 185 * The StrictMode "critical time span" objects to catch animation 186 * stutters. Non-null when a time-sensitive animation is 187 * in-flight. Must call finish() on them when done animating. 188 * These are no-ops on user builds. 189 */ 190 private StrictMode.Span mScrollStrictSpan = null; // aka "drag" 191 @UnsupportedAppUsage 192 private StrictMode.Span mFlingStrictSpan = null; 193 194 /** 195 * Sentinel value for no current active pointer. 196 * Used by {@link #mActivePointerId}. 197 */ 198 private static final int INVALID_POINTER = -1; 199 200 private SavedState mSavedState; 201 ScrollView(Context context)202 public ScrollView(Context context) { 203 this(context, null); 204 } 205 ScrollView(Context context, AttributeSet attrs)206 public ScrollView(Context context, AttributeSet attrs) { 207 this(context, attrs, com.android.internal.R.attr.scrollViewStyle); 208 } 209 ScrollView(Context context, AttributeSet attrs, int defStyleAttr)210 public ScrollView(Context context, AttributeSet attrs, int defStyleAttr) { 211 this(context, attrs, defStyleAttr, 0); 212 } 213 ScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)214 public ScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 215 super(context, attrs, defStyleAttr, defStyleRes); 216 initScrollView(); 217 218 final TypedArray a = context.obtainStyledAttributes( 219 attrs, com.android.internal.R.styleable.ScrollView, defStyleAttr, defStyleRes); 220 saveAttributeDataForStyleable(context, com.android.internal.R.styleable.ScrollView, 221 attrs, a, defStyleAttr, defStyleRes); 222 223 setFillViewport(a.getBoolean(R.styleable.ScrollView_fillViewport, false)); 224 225 a.recycle(); 226 227 if (context.getResources().getConfiguration().uiMode == Configuration.UI_MODE_TYPE_WATCH) { 228 setRevealOnFocusHint(false); 229 } 230 } 231 232 @Override shouldDelayChildPressedState()233 public boolean shouldDelayChildPressedState() { 234 return true; 235 } 236 237 @Override getTopFadingEdgeStrength()238 protected float getTopFadingEdgeStrength() { 239 if (getChildCount() == 0) { 240 return 0.0f; 241 } 242 243 final int length = getVerticalFadingEdgeLength(); 244 if (mScrollY < length) { 245 return mScrollY / (float) length; 246 } 247 248 return 1.0f; 249 } 250 251 @Override getBottomFadingEdgeStrength()252 protected float getBottomFadingEdgeStrength() { 253 if (getChildCount() == 0) { 254 return 0.0f; 255 } 256 257 final int length = getVerticalFadingEdgeLength(); 258 final int bottomEdge = getHeight() - mPaddingBottom; 259 final int span = getChildAt(0).getBottom() - mScrollY - bottomEdge; 260 if (span < length) { 261 return span / (float) length; 262 } 263 264 return 1.0f; 265 } 266 267 /** 268 * Sets the edge effect color for both top and bottom edge effects. 269 * 270 * @param color The color for the edge effects. 271 * @see #setTopEdgeEffectColor(int) 272 * @see #setBottomEdgeEffectColor(int) 273 * @see #getTopEdgeEffectColor() 274 * @see #getBottomEdgeEffectColor() 275 */ setEdgeEffectColor(@olorInt int color)276 public void setEdgeEffectColor(@ColorInt int color) { 277 setTopEdgeEffectColor(color); 278 setBottomEdgeEffectColor(color); 279 } 280 281 /** 282 * Sets the bottom edge effect color. 283 * 284 * @param color The color for the bottom edge effect. 285 * @see #setTopEdgeEffectColor(int) 286 * @see #setEdgeEffectColor(int) 287 * @see #getTopEdgeEffectColor() 288 * @see #getBottomEdgeEffectColor() 289 */ setBottomEdgeEffectColor(@olorInt int color)290 public void setBottomEdgeEffectColor(@ColorInt int color) { 291 mEdgeGlowBottom.setColor(color); 292 } 293 294 /** 295 * Sets the top edge effect color. 296 * 297 * @param color The color for the top edge effect. 298 * @see #setBottomEdgeEffectColor(int) 299 * @see #setEdgeEffectColor(int) 300 * @see #getTopEdgeEffectColor() 301 * @see #getBottomEdgeEffectColor() 302 */ setTopEdgeEffectColor(@olorInt int color)303 public void setTopEdgeEffectColor(@ColorInt int color) { 304 mEdgeGlowTop.setColor(color); 305 } 306 307 /** 308 * Returns the top edge effect color. 309 * 310 * @return The top edge effect color. 311 * @see #setEdgeEffectColor(int) 312 * @see #setTopEdgeEffectColor(int) 313 * @see #setBottomEdgeEffectColor(int) 314 * @see #getBottomEdgeEffectColor() 315 */ 316 @ColorInt getTopEdgeEffectColor()317 public int getTopEdgeEffectColor() { 318 return mEdgeGlowTop.getColor(); 319 } 320 321 /** 322 * Returns the bottom edge effect color. 323 * 324 * @return The bottom edge effect color. 325 * @see #setEdgeEffectColor(int) 326 * @see #setTopEdgeEffectColor(int) 327 * @see #setBottomEdgeEffectColor(int) 328 * @see #getTopEdgeEffectColor() 329 */ 330 @ColorInt getBottomEdgeEffectColor()331 public int getBottomEdgeEffectColor() { 332 return mEdgeGlowBottom.getColor(); 333 } 334 335 /** 336 * @return The maximum amount this scroll view will scroll in response to 337 * an arrow event. 338 */ getMaxScrollAmount()339 public int getMaxScrollAmount() { 340 return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop)); 341 } 342 343 initScrollView()344 private void initScrollView() { 345 mScroller = new OverScroller(getContext()); 346 setFocusable(true); 347 setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); 348 setWillNotDraw(false); 349 final ViewConfiguration configuration = ViewConfiguration.get(mContext); 350 mTouchSlop = configuration.getScaledTouchSlop(); 351 mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); 352 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 353 mOverscrollDistance = configuration.getScaledOverscrollDistance(); 354 mOverflingDistance = configuration.getScaledOverflingDistance(); 355 mVerticalScrollFactor = configuration.getScaledVerticalScrollFactor(); 356 } 357 358 @Override addView(View child)359 public void addView(View child) { 360 if (getChildCount() > 0) { 361 throw new IllegalStateException("ScrollView can host only one direct child"); 362 } 363 364 super.addView(child); 365 } 366 367 @Override addView(View child, int index)368 public void addView(View child, int index) { 369 if (getChildCount() > 0) { 370 throw new IllegalStateException("ScrollView can host only one direct child"); 371 } 372 373 super.addView(child, index); 374 } 375 376 @Override addView(View child, ViewGroup.LayoutParams params)377 public void addView(View child, ViewGroup.LayoutParams params) { 378 if (getChildCount() > 0) { 379 throw new IllegalStateException("ScrollView can host only one direct child"); 380 } 381 382 super.addView(child, params); 383 } 384 385 @Override addView(View child, int index, ViewGroup.LayoutParams params)386 public void addView(View child, int index, ViewGroup.LayoutParams params) { 387 if (getChildCount() > 0) { 388 throw new IllegalStateException("ScrollView can host only one direct child"); 389 } 390 391 super.addView(child, index, params); 392 } 393 394 /** 395 * @return Returns true this ScrollView can be scrolled 396 */ 397 @UnsupportedAppUsage canScroll()398 private boolean canScroll() { 399 View child = getChildAt(0); 400 if (child != null) { 401 int childHeight = child.getHeight(); 402 return getHeight() < childHeight + mPaddingTop + mPaddingBottom; 403 } 404 return false; 405 } 406 407 /** 408 * Indicates whether this ScrollView's content is stretched to fill the viewport. 409 * 410 * @return True if the content fills the viewport, false otherwise. 411 * 412 * @attr ref android.R.styleable#ScrollView_fillViewport 413 */ 414 @InspectableProperty isFillViewport()415 public boolean isFillViewport() { 416 return mFillViewport; 417 } 418 419 /** 420 * Indicates this ScrollView whether it should stretch its content height to fill 421 * the viewport or not. 422 * 423 * @param fillViewport True to stretch the content's height to the viewport's 424 * boundaries, false otherwise. 425 * 426 * @attr ref android.R.styleable#ScrollView_fillViewport 427 */ setFillViewport(boolean fillViewport)428 public void setFillViewport(boolean fillViewport) { 429 if (fillViewport != mFillViewport) { 430 mFillViewport = fillViewport; 431 requestLayout(); 432 } 433 } 434 435 /** 436 * @return Whether arrow scrolling will animate its transition. 437 */ isSmoothScrollingEnabled()438 public boolean isSmoothScrollingEnabled() { 439 return mSmoothScrollingEnabled; 440 } 441 442 /** 443 * Set whether arrow scrolling will animate its transition. 444 * @param smoothScrollingEnabled whether arrow scrolling will animate its transition 445 */ setSmoothScrollingEnabled(boolean smoothScrollingEnabled)446 public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) { 447 mSmoothScrollingEnabled = smoothScrollingEnabled; 448 } 449 450 @Override onMeasure(int widthMeasureSpec, int heightMeasureSpec)451 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 452 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 453 454 if (!mFillViewport) { 455 return; 456 } 457 458 final int heightMode = MeasureSpec.getMode(heightMeasureSpec); 459 if (heightMode == MeasureSpec.UNSPECIFIED) { 460 return; 461 } 462 463 if (getChildCount() > 0) { 464 final View child = getChildAt(0); 465 final int widthPadding; 466 final int heightPadding; 467 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 468 final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); 469 if (targetSdkVersion >= VERSION_CODES.M) { 470 widthPadding = mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin; 471 heightPadding = mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin; 472 } else { 473 widthPadding = mPaddingLeft + mPaddingRight; 474 heightPadding = mPaddingTop + mPaddingBottom; 475 } 476 477 final int desiredHeight = getMeasuredHeight() - heightPadding; 478 if (child.getMeasuredHeight() < desiredHeight) { 479 final int childWidthMeasureSpec = getChildMeasureSpec( 480 widthMeasureSpec, widthPadding, lp.width); 481 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( 482 desiredHeight, MeasureSpec.EXACTLY); 483 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 484 } 485 } 486 } 487 488 @Override dispatchKeyEvent(KeyEvent event)489 public boolean dispatchKeyEvent(KeyEvent event) { 490 // Let the focused view and/or our descendants get the key first 491 return super.dispatchKeyEvent(event) || executeKeyEvent(event); 492 } 493 494 /** 495 * You can call this function yourself to have the scroll view perform 496 * scrolling from a key event, just as if the event had been dispatched to 497 * it by the view hierarchy. 498 * 499 * @param event The key event to execute. 500 * @return Return true if the event was handled, else false. 501 */ executeKeyEvent(KeyEvent event)502 public boolean executeKeyEvent(KeyEvent event) { 503 mTempRect.setEmpty(); 504 505 if (!canScroll()) { 506 if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) { 507 View currentFocused = findFocus(); 508 if (currentFocused == this) currentFocused = null; 509 View nextFocused = FocusFinder.getInstance().findNextFocus(this, 510 currentFocused, View.FOCUS_DOWN); 511 return nextFocused != null 512 && nextFocused != this 513 && nextFocused.requestFocus(View.FOCUS_DOWN); 514 } 515 return false; 516 } 517 518 boolean handled = false; 519 if (event.getAction() == KeyEvent.ACTION_DOWN) { 520 switch (event.getKeyCode()) { 521 case KeyEvent.KEYCODE_DPAD_UP: 522 if (!event.isAltPressed()) { 523 handled = arrowScroll(View.FOCUS_UP); 524 } else { 525 handled = fullScroll(View.FOCUS_UP); 526 } 527 break; 528 case KeyEvent.KEYCODE_DPAD_DOWN: 529 if (!event.isAltPressed()) { 530 handled = arrowScroll(View.FOCUS_DOWN); 531 } else { 532 handled = fullScroll(View.FOCUS_DOWN); 533 } 534 break; 535 case KeyEvent.KEYCODE_SPACE: 536 pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN); 537 break; 538 } 539 } 540 541 return handled; 542 } 543 inChild(int x, int y)544 private boolean inChild(int x, int y) { 545 if (getChildCount() > 0) { 546 final int scrollY = mScrollY; 547 final View child = getChildAt(0); 548 return !(y < child.getTop() - scrollY 549 || y >= child.getBottom() - scrollY 550 || x < child.getLeft() 551 || x >= child.getRight()); 552 } 553 return false; 554 } 555 initOrResetVelocityTracker()556 private void initOrResetVelocityTracker() { 557 if (mVelocityTracker == null) { 558 mVelocityTracker = VelocityTracker.obtain(); 559 } else { 560 mVelocityTracker.clear(); 561 } 562 } 563 initVelocityTrackerIfNotExists()564 private void initVelocityTrackerIfNotExists() { 565 if (mVelocityTracker == null) { 566 mVelocityTracker = VelocityTracker.obtain(); 567 } 568 } 569 recycleVelocityTracker()570 private void recycleVelocityTracker() { 571 if (mVelocityTracker != null) { 572 mVelocityTracker.recycle(); 573 mVelocityTracker = null; 574 } 575 } 576 577 @Override requestDisallowInterceptTouchEvent(boolean disallowIntercept)578 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 579 if (disallowIntercept) { 580 recycleVelocityTracker(); 581 } 582 super.requestDisallowInterceptTouchEvent(disallowIntercept); 583 } 584 585 586 @Override onInterceptTouchEvent(MotionEvent ev)587 public boolean onInterceptTouchEvent(MotionEvent ev) { 588 /* 589 * This method JUST determines whether we want to intercept the motion. 590 * If we return true, onMotionEvent will be called and we do the actual 591 * scrolling there. 592 */ 593 594 /* 595 * Shortcut the most recurring case: the user is in the dragging 596 * state and he is moving his finger. We want to intercept this 597 * motion. 598 */ 599 final int action = ev.getAction(); 600 if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { 601 return true; 602 } 603 604 if (super.onInterceptTouchEvent(ev)) { 605 return true; 606 } 607 608 /* 609 * Don't try to intercept touch if we can't scroll anyway. 610 */ 611 if (getScrollY() == 0 && !canScrollVertically(1)) { 612 return false; 613 } 614 615 switch (action & MotionEvent.ACTION_MASK) { 616 case MotionEvent.ACTION_MOVE: { 617 /* 618 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 619 * whether the user has moved far enough from his original down touch. 620 */ 621 622 /* 623 * Locally do absolute value. mLastMotionY is set to the y value 624 * of the down event. 625 */ 626 final int activePointerId = mActivePointerId; 627 if (activePointerId == INVALID_POINTER) { 628 // If we don't have a valid id, the touch down wasn't on content. 629 break; 630 } 631 632 final int pointerIndex = ev.findPointerIndex(activePointerId); 633 if (pointerIndex == -1) { 634 Log.e(TAG, "Invalid pointerId=" + activePointerId 635 + " in onInterceptTouchEvent"); 636 break; 637 } 638 639 final int y = (int) ev.getY(pointerIndex); 640 final int yDiff = Math.abs(y - mLastMotionY); 641 if (yDiff > mTouchSlop && (getNestedScrollAxes() & SCROLL_AXIS_VERTICAL) == 0) { 642 mIsBeingDragged = true; 643 mLastMotionY = y; 644 initVelocityTrackerIfNotExists(); 645 mVelocityTracker.addMovement(ev); 646 mNestedYOffset = 0; 647 if (mScrollStrictSpan == null) { 648 mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll"); 649 } 650 final ViewParent parent = getParent(); 651 if (parent != null) { 652 parent.requestDisallowInterceptTouchEvent(true); 653 } 654 } 655 break; 656 } 657 658 case MotionEvent.ACTION_DOWN: { 659 final int y = (int) ev.getY(); 660 if (!inChild((int) ev.getX(), (int) y)) { 661 mIsBeingDragged = false; 662 recycleVelocityTracker(); 663 break; 664 } 665 666 /* 667 * Remember location of down touch. 668 * ACTION_DOWN always refers to pointer index 0. 669 */ 670 mLastMotionY = y; 671 mActivePointerId = ev.getPointerId(0); 672 673 initOrResetVelocityTracker(); 674 mVelocityTracker.addMovement(ev); 675 /* 676 * If being flinged and user touches the screen, initiate drag; 677 * otherwise don't. mScroller.isFinished should be false when 678 * being flinged. We need to call computeScrollOffset() first so that 679 * isFinished() is correct. 680 */ 681 mScroller.computeScrollOffset(); 682 mIsBeingDragged = !mScroller.isFinished(); 683 if (mIsBeingDragged && mScrollStrictSpan == null) { 684 mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll"); 685 } 686 startNestedScroll(SCROLL_AXIS_VERTICAL); 687 break; 688 } 689 690 case MotionEvent.ACTION_CANCEL: 691 case MotionEvent.ACTION_UP: 692 /* Release the drag */ 693 mIsBeingDragged = false; 694 mActivePointerId = INVALID_POINTER; 695 recycleVelocityTracker(); 696 if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) { 697 postInvalidateOnAnimation(); 698 } 699 stopNestedScroll(); 700 break; 701 case MotionEvent.ACTION_POINTER_UP: 702 onSecondaryPointerUp(ev); 703 break; 704 } 705 706 /* 707 * The only time we want to intercept motion events is if we are in the 708 * drag mode. 709 */ 710 return mIsBeingDragged; 711 } 712 shouldDisplayEdgeEffects()713 private boolean shouldDisplayEdgeEffects() { 714 return getOverScrollMode() != OVER_SCROLL_NEVER; 715 } 716 717 @Override onTouchEvent(MotionEvent ev)718 public boolean onTouchEvent(MotionEvent ev) { 719 initVelocityTrackerIfNotExists(); 720 721 MotionEvent vtev = MotionEvent.obtain(ev); 722 723 final int actionMasked = ev.getActionMasked(); 724 725 if (actionMasked == MotionEvent.ACTION_DOWN) { 726 mNestedYOffset = 0; 727 } 728 vtev.offsetLocation(0, mNestedYOffset); 729 730 switch (actionMasked) { 731 case MotionEvent.ACTION_DOWN: { 732 if (getChildCount() == 0) { 733 return false; 734 } 735 if ((mIsBeingDragged = !mScroller.isFinished())) { 736 final ViewParent parent = getParent(); 737 if (parent != null) { 738 parent.requestDisallowInterceptTouchEvent(true); 739 } 740 } 741 742 /* 743 * If being flinged and user touches, stop the fling. isFinished 744 * will be false if being flinged. 745 */ 746 if (!mScroller.isFinished()) { 747 mScroller.abortAnimation(); 748 if (mFlingStrictSpan != null) { 749 mFlingStrictSpan.finish(); 750 mFlingStrictSpan = null; 751 } 752 } 753 754 // Remember where the motion event started 755 mLastMotionY = (int) ev.getY(); 756 mActivePointerId = ev.getPointerId(0); 757 startNestedScroll(SCROLL_AXIS_VERTICAL); 758 break; 759 } 760 case MotionEvent.ACTION_MOVE: 761 final int activePointerIndex = ev.findPointerIndex(mActivePointerId); 762 if (activePointerIndex == -1) { 763 Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent"); 764 break; 765 } 766 767 final int y = (int) ev.getY(activePointerIndex); 768 int deltaY = mLastMotionY - y; 769 if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) { 770 deltaY -= mScrollConsumed[1]; 771 vtev.offsetLocation(0, mScrollOffset[1]); 772 mNestedYOffset += mScrollOffset[1]; 773 } 774 if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) { 775 final ViewParent parent = getParent(); 776 if (parent != null) { 777 parent.requestDisallowInterceptTouchEvent(true); 778 } 779 mIsBeingDragged = true; 780 if (deltaY > 0) { 781 deltaY -= mTouchSlop; 782 } else { 783 deltaY += mTouchSlop; 784 } 785 } 786 if (mIsBeingDragged) { 787 // Scroll to follow the motion event 788 mLastMotionY = y - mScrollOffset[1]; 789 790 final int oldY = mScrollY; 791 final int range = getScrollRange(); 792 final int overscrollMode = getOverScrollMode(); 793 boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS || 794 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); 795 796 // Calling overScrollBy will call onOverScrolled, which 797 // calls onScrollChanged if applicable. 798 if (overScrollBy(0, deltaY, 0, mScrollY, 0, range, 0, mOverscrollDistance, true) 799 && !hasNestedScrollingParent()) { 800 // Break our velocity if we hit a scroll barrier. 801 mVelocityTracker.clear(); 802 } 803 804 final int scrolledDeltaY = mScrollY - oldY; 805 final int unconsumedY = deltaY - scrolledDeltaY; 806 if (dispatchNestedScroll(0, scrolledDeltaY, 0, unconsumedY, mScrollOffset)) { 807 mLastMotionY -= mScrollOffset[1]; 808 vtev.offsetLocation(0, mScrollOffset[1]); 809 mNestedYOffset += mScrollOffset[1]; 810 } else if (canOverscroll) { 811 final int pulledToY = oldY + deltaY; 812 if (pulledToY < 0) { 813 mEdgeGlowTop.onPull((float) deltaY / getHeight(), 814 ev.getX(activePointerIndex) / getWidth()); 815 if (!mEdgeGlowBottom.isFinished()) { 816 mEdgeGlowBottom.onRelease(); 817 } 818 } else if (pulledToY > range) { 819 mEdgeGlowBottom.onPull((float) deltaY / getHeight(), 820 1.f - ev.getX(activePointerIndex) / getWidth()); 821 if (!mEdgeGlowTop.isFinished()) { 822 mEdgeGlowTop.onRelease(); 823 } 824 } 825 if (shouldDisplayEdgeEffects() 826 && (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) { 827 postInvalidateOnAnimation(); 828 } 829 } 830 } 831 break; 832 case MotionEvent.ACTION_UP: 833 if (mIsBeingDragged) { 834 final VelocityTracker velocityTracker = mVelocityTracker; 835 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 836 int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId); 837 838 if ((Math.abs(initialVelocity) > mMinimumVelocity)) { 839 flingWithNestedDispatch(-initialVelocity); 840 } else if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, 841 getScrollRange())) { 842 postInvalidateOnAnimation(); 843 } 844 845 mActivePointerId = INVALID_POINTER; 846 endDrag(); 847 } 848 break; 849 case MotionEvent.ACTION_CANCEL: 850 if (mIsBeingDragged && getChildCount() > 0) { 851 if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) { 852 postInvalidateOnAnimation(); 853 } 854 mActivePointerId = INVALID_POINTER; 855 endDrag(); 856 } 857 break; 858 case MotionEvent.ACTION_POINTER_DOWN: { 859 final int index = ev.getActionIndex(); 860 mLastMotionY = (int) ev.getY(index); 861 mActivePointerId = ev.getPointerId(index); 862 break; 863 } 864 case MotionEvent.ACTION_POINTER_UP: 865 onSecondaryPointerUp(ev); 866 mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId)); 867 break; 868 } 869 870 if (mVelocityTracker != null) { 871 mVelocityTracker.addMovement(vtev); 872 } 873 vtev.recycle(); 874 return true; 875 } 876 onSecondaryPointerUp(MotionEvent ev)877 private void onSecondaryPointerUp(MotionEvent ev) { 878 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> 879 MotionEvent.ACTION_POINTER_INDEX_SHIFT; 880 final int pointerId = ev.getPointerId(pointerIndex); 881 if (pointerId == mActivePointerId) { 882 // This was our active pointer going up. Choose a new 883 // active pointer and adjust accordingly. 884 // TODO: Make this decision more intelligent. 885 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 886 mLastMotionY = (int) ev.getY(newPointerIndex); 887 mActivePointerId = ev.getPointerId(newPointerIndex); 888 if (mVelocityTracker != null) { 889 mVelocityTracker.clear(); 890 } 891 } 892 } 893 894 @Override onGenericMotionEvent(MotionEvent event)895 public boolean onGenericMotionEvent(MotionEvent event) { 896 switch (event.getAction()) { 897 case MotionEvent.ACTION_SCROLL: 898 final float axisValue; 899 if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 900 axisValue = event.getAxisValue(MotionEvent.AXIS_VSCROLL); 901 } else if (event.isFromSource(InputDevice.SOURCE_ROTARY_ENCODER)) { 902 axisValue = event.getAxisValue(MotionEvent.AXIS_SCROLL); 903 } else { 904 axisValue = 0; 905 } 906 907 final int delta = Math.round(axisValue * mVerticalScrollFactor); 908 if (delta != 0) { 909 final int range = getScrollRange(); 910 int oldScrollY = mScrollY; 911 int newScrollY = oldScrollY - delta; 912 if (newScrollY < 0) { 913 newScrollY = 0; 914 } else if (newScrollY > range) { 915 newScrollY = range; 916 } 917 if (newScrollY != oldScrollY) { 918 super.scrollTo(mScrollX, newScrollY); 919 return true; 920 } 921 } 922 break; 923 } 924 925 return super.onGenericMotionEvent(event); 926 } 927 928 @Override onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)929 protected void onOverScrolled(int scrollX, int scrollY, 930 boolean clampedX, boolean clampedY) { 931 // Treat animating scrolls differently; see #computeScroll() for why. 932 if (!mScroller.isFinished()) { 933 final int oldX = mScrollX; 934 final int oldY = mScrollY; 935 mScrollX = scrollX; 936 mScrollY = scrollY; 937 invalidateParentIfNeeded(); 938 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 939 if (clampedY) { 940 mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange()); 941 } 942 } else { 943 super.scrollTo(scrollX, scrollY); 944 } 945 946 awakenScrollBars(); 947 } 948 949 /** @hide */ 950 @Override performAccessibilityActionInternal(int action, Bundle arguments)951 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 952 if (super.performAccessibilityActionInternal(action, arguments)) { 953 return true; 954 } 955 if (!isEnabled()) { 956 return false; 957 } 958 switch (action) { 959 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: 960 case R.id.accessibilityActionScrollDown: { 961 final int viewportHeight = getHeight() - mPaddingBottom - mPaddingTop; 962 final int targetScrollY = Math.min(mScrollY + viewportHeight, getScrollRange()); 963 if (targetScrollY != mScrollY) { 964 smoothScrollTo(0, targetScrollY); 965 return true; 966 } 967 } return false; 968 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: 969 case R.id.accessibilityActionScrollUp: { 970 final int viewportHeight = getHeight() - mPaddingBottom - mPaddingTop; 971 final int targetScrollY = Math.max(mScrollY - viewportHeight, 0); 972 if (targetScrollY != mScrollY) { 973 smoothScrollTo(0, targetScrollY); 974 return true; 975 } 976 } return false; 977 } 978 return false; 979 } 980 981 @Override getAccessibilityClassName()982 public CharSequence getAccessibilityClassName() { 983 return ScrollView.class.getName(); 984 } 985 986 /** @hide */ 987 @Override onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info)988 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 989 super.onInitializeAccessibilityNodeInfoInternal(info); 990 if (isEnabled()) { 991 final int scrollRange = getScrollRange(); 992 if (scrollRange > 0) { 993 info.setScrollable(true); 994 if (mScrollY > 0) { 995 info.addAction( 996 AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD); 997 info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_UP); 998 } 999 if (mScrollY < scrollRange) { 1000 info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD); 1001 info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_DOWN); 1002 } 1003 } 1004 } 1005 } 1006 1007 /** @hide */ 1008 @Override onInitializeAccessibilityEventInternal(AccessibilityEvent event)1009 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 1010 super.onInitializeAccessibilityEventInternal(event); 1011 final boolean scrollable = getScrollRange() > 0; 1012 event.setScrollable(scrollable); 1013 event.setMaxScrollX(mScrollX); 1014 event.setMaxScrollY(getScrollRange()); 1015 } 1016 getScrollRange()1017 private int getScrollRange() { 1018 int scrollRange = 0; 1019 if (getChildCount() > 0) { 1020 View child = getChildAt(0); 1021 scrollRange = Math.max(0, 1022 child.getHeight() - (getHeight() - mPaddingBottom - mPaddingTop)); 1023 } 1024 return scrollRange; 1025 } 1026 1027 /** 1028 * <p> 1029 * Finds the next focusable component that fits in the specified bounds. 1030 * </p> 1031 * 1032 * @param topFocus look for a candidate is the one at the top of the bounds 1033 * if topFocus is true, or at the bottom of the bounds if topFocus is 1034 * false 1035 * @param top the top offset of the bounds in which a focusable must be 1036 * found 1037 * @param bottom the bottom offset of the bounds in which a focusable must 1038 * be found 1039 * @return the next focusable component in the bounds or null if none can 1040 * be found 1041 */ findFocusableViewInBounds(boolean topFocus, int top, int bottom)1042 private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) { 1043 1044 List<View> focusables = getFocusables(View.FOCUS_FORWARD); 1045 View focusCandidate = null; 1046 1047 /* 1048 * A fully contained focusable is one where its top is below the bound's 1049 * top, and its bottom is above the bound's bottom. A partially 1050 * contained focusable is one where some part of it is within the 1051 * bounds, but it also has some part that is not within bounds. A fully contained 1052 * focusable is preferred to a partially contained focusable. 1053 */ 1054 boolean foundFullyContainedFocusable = false; 1055 1056 int count = focusables.size(); 1057 for (int i = 0; i < count; i++) { 1058 View view = focusables.get(i); 1059 int viewTop = view.getTop(); 1060 int viewBottom = view.getBottom(); 1061 1062 if (top < viewBottom && viewTop < bottom) { 1063 /* 1064 * the focusable is in the target area, it is a candidate for 1065 * focusing 1066 */ 1067 1068 final boolean viewIsFullyContained = (top < viewTop) && 1069 (viewBottom < bottom); 1070 1071 if (focusCandidate == null) { 1072 /* No candidate, take this one */ 1073 focusCandidate = view; 1074 foundFullyContainedFocusable = viewIsFullyContained; 1075 } else { 1076 final boolean viewIsCloserToBoundary = 1077 (topFocus && viewTop < focusCandidate.getTop()) || 1078 (!topFocus && viewBottom > focusCandidate 1079 .getBottom()); 1080 1081 if (foundFullyContainedFocusable) { 1082 if (viewIsFullyContained && viewIsCloserToBoundary) { 1083 /* 1084 * We're dealing with only fully contained views, so 1085 * it has to be closer to the boundary to beat our 1086 * candidate 1087 */ 1088 focusCandidate = view; 1089 } 1090 } else { 1091 if (viewIsFullyContained) { 1092 /* Any fully contained view beats a partially contained view */ 1093 focusCandidate = view; 1094 foundFullyContainedFocusable = true; 1095 } else if (viewIsCloserToBoundary) { 1096 /* 1097 * Partially contained view beats another partially 1098 * contained view if it's closer 1099 */ 1100 focusCandidate = view; 1101 } 1102 } 1103 } 1104 } 1105 } 1106 1107 return focusCandidate; 1108 } 1109 1110 /** 1111 * <p>Handles scrolling in response to a "page up/down" shortcut press. This 1112 * method will scroll the view by one page up or down and give the focus 1113 * to the topmost/bottommost component in the new visible area. If no 1114 * component is a good candidate for focus, this scrollview reclaims the 1115 * focus.</p> 1116 * 1117 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 1118 * to go one page up or 1119 * {@link android.view.View#FOCUS_DOWN} to go one page down 1120 * @return true if the key event is consumed by this method, false otherwise 1121 */ pageScroll(int direction)1122 public boolean pageScroll(int direction) { 1123 boolean down = direction == View.FOCUS_DOWN; 1124 int height = getHeight(); 1125 1126 if (down) { 1127 mTempRect.top = getScrollY() + height; 1128 int count = getChildCount(); 1129 if (count > 0) { 1130 View view = getChildAt(count - 1); 1131 if (mTempRect.top + height > view.getBottom()) { 1132 mTempRect.top = view.getBottom() - height; 1133 } 1134 } 1135 } else { 1136 mTempRect.top = getScrollY() - height; 1137 if (mTempRect.top < 0) { 1138 mTempRect.top = 0; 1139 } 1140 } 1141 mTempRect.bottom = mTempRect.top + height; 1142 1143 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 1144 } 1145 1146 /** 1147 * <p>Handles scrolling in response to a "home/end" shortcut press. This 1148 * method will scroll the view to the top or bottom and give the focus 1149 * to the topmost/bottommost component in the new visible area. If no 1150 * component is a good candidate for focus, this scrollview reclaims the 1151 * focus.</p> 1152 * 1153 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 1154 * to go the top of the view or 1155 * {@link android.view.View#FOCUS_DOWN} to go the bottom 1156 * @return true if the key event is consumed by this method, false otherwise 1157 */ fullScroll(int direction)1158 public boolean fullScroll(int direction) { 1159 boolean down = direction == View.FOCUS_DOWN; 1160 int height = getHeight(); 1161 1162 mTempRect.top = 0; 1163 mTempRect.bottom = height; 1164 1165 if (down) { 1166 int count = getChildCount(); 1167 if (count > 0) { 1168 View view = getChildAt(count - 1); 1169 mTempRect.bottom = view.getBottom() + mPaddingBottom; 1170 mTempRect.top = mTempRect.bottom - height; 1171 } 1172 } 1173 1174 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 1175 } 1176 1177 /** 1178 * <p>Scrolls the view to make the area defined by <code>top</code> and 1179 * <code>bottom</code> visible. This method attempts to give the focus 1180 * to a component visible in this area. If no component can be focused in 1181 * the new visible area, the focus is reclaimed by this ScrollView.</p> 1182 * 1183 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 1184 * to go upward, {@link android.view.View#FOCUS_DOWN} to downward 1185 * @param top the top offset of the new area to be made visible 1186 * @param bottom the bottom offset of the new area to be made visible 1187 * @return true if the key event is consumed by this method, false otherwise 1188 */ scrollAndFocus(int direction, int top, int bottom)1189 private boolean scrollAndFocus(int direction, int top, int bottom) { 1190 boolean handled = true; 1191 1192 int height = getHeight(); 1193 int containerTop = getScrollY(); 1194 int containerBottom = containerTop + height; 1195 boolean up = direction == View.FOCUS_UP; 1196 1197 View newFocused = findFocusableViewInBounds(up, top, bottom); 1198 if (newFocused == null) { 1199 newFocused = this; 1200 } 1201 1202 if (top >= containerTop && bottom <= containerBottom) { 1203 handled = false; 1204 } else { 1205 int delta = up ? (top - containerTop) : (bottom - containerBottom); 1206 doScrollY(delta); 1207 } 1208 1209 if (newFocused != findFocus()) newFocused.requestFocus(direction); 1210 1211 return handled; 1212 } 1213 1214 /** 1215 * Handle scrolling in response to an up or down arrow click. 1216 * 1217 * @param direction The direction corresponding to the arrow key that was 1218 * pressed 1219 * @return True if we consumed the event, false otherwise 1220 */ arrowScroll(int direction)1221 public boolean arrowScroll(int direction) { 1222 1223 View currentFocused = findFocus(); 1224 if (currentFocused == this) currentFocused = null; 1225 1226 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); 1227 1228 final int maxJump = getMaxScrollAmount(); 1229 1230 if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) { 1231 nextFocused.getDrawingRect(mTempRect); 1232 offsetDescendantRectToMyCoords(nextFocused, mTempRect); 1233 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1234 doScrollY(scrollDelta); 1235 nextFocused.requestFocus(direction); 1236 } else { 1237 // no new focus 1238 int scrollDelta = maxJump; 1239 1240 if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { 1241 scrollDelta = getScrollY(); 1242 } else if (direction == View.FOCUS_DOWN) { 1243 if (getChildCount() > 0) { 1244 int daBottom = getChildAt(0).getBottom(); 1245 int screenBottom = getScrollY() + getHeight() - mPaddingBottom; 1246 if (daBottom - screenBottom < maxJump) { 1247 scrollDelta = daBottom - screenBottom; 1248 } 1249 } 1250 } 1251 if (scrollDelta == 0) { 1252 return false; 1253 } 1254 doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); 1255 } 1256 1257 if (currentFocused != null && currentFocused.isFocused() 1258 && isOffScreen(currentFocused)) { 1259 // previously focused item still has focus and is off screen, give 1260 // it up (take it back to ourselves) 1261 // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are 1262 // sure to 1263 // get it) 1264 final int descendantFocusability = getDescendantFocusability(); // save 1265 setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); 1266 requestFocus(); 1267 setDescendantFocusability(descendantFocusability); // restore 1268 } 1269 return true; 1270 } 1271 1272 /** 1273 * @return whether the descendant of this scroll view is scrolled off 1274 * screen. 1275 */ isOffScreen(View descendant)1276 private boolean isOffScreen(View descendant) { 1277 return !isWithinDeltaOfScreen(descendant, 0, getHeight()); 1278 } 1279 1280 /** 1281 * @return whether the descendant of this scroll view is within delta 1282 * pixels of being on the screen. 1283 */ isWithinDeltaOfScreen(View descendant, int delta, int height)1284 private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) { 1285 descendant.getDrawingRect(mTempRect); 1286 offsetDescendantRectToMyCoords(descendant, mTempRect); 1287 1288 return (mTempRect.bottom + delta) >= getScrollY() 1289 && (mTempRect.top - delta) <= (getScrollY() + height); 1290 } 1291 1292 /** 1293 * Smooth scroll by a Y delta 1294 * 1295 * @param delta the number of pixels to scroll by on the Y axis 1296 */ doScrollY(int delta)1297 private void doScrollY(int delta) { 1298 if (delta != 0) { 1299 if (mSmoothScrollingEnabled) { 1300 smoothScrollBy(0, delta); 1301 } else { 1302 scrollBy(0, delta); 1303 } 1304 } 1305 } 1306 1307 /** 1308 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 1309 * 1310 * @param dx the number of pixels to scroll by on the X axis 1311 * @param dy the number of pixels to scroll by on the Y axis 1312 */ smoothScrollBy(int dx, int dy)1313 public final void smoothScrollBy(int dx, int dy) { 1314 if (getChildCount() == 0) { 1315 // Nothing to do. 1316 return; 1317 } 1318 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 1319 if (duration > ANIMATED_SCROLL_GAP) { 1320 final int height = getHeight() - mPaddingBottom - mPaddingTop; 1321 final int bottom = getChildAt(0).getHeight(); 1322 final int maxY = Math.max(0, bottom - height); 1323 final int scrollY = mScrollY; 1324 dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY; 1325 1326 mScroller.startScroll(mScrollX, scrollY, 0, dy); 1327 postInvalidateOnAnimation(); 1328 } else { 1329 if (!mScroller.isFinished()) { 1330 mScroller.abortAnimation(); 1331 if (mFlingStrictSpan != null) { 1332 mFlingStrictSpan.finish(); 1333 mFlingStrictSpan = null; 1334 } 1335 } 1336 scrollBy(dx, dy); 1337 } 1338 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 1339 } 1340 1341 /** 1342 * Like {@link #scrollTo}, but scroll smoothly instead of immediately. 1343 * 1344 * @param x the position where to scroll on the X axis 1345 * @param y the position where to scroll on the Y axis 1346 */ smoothScrollTo(int x, int y)1347 public final void smoothScrollTo(int x, int y) { 1348 smoothScrollBy(x - mScrollX, y - mScrollY); 1349 } 1350 1351 /** 1352 * <p>The scroll range of a scroll view is the overall height of all of its 1353 * children.</p> 1354 */ 1355 @Override computeVerticalScrollRange()1356 protected int computeVerticalScrollRange() { 1357 final int count = getChildCount(); 1358 final int contentHeight = getHeight() - mPaddingBottom - mPaddingTop; 1359 if (count == 0) { 1360 return contentHeight; 1361 } 1362 1363 int scrollRange = getChildAt(0).getBottom(); 1364 final int scrollY = mScrollY; 1365 final int overscrollBottom = Math.max(0, scrollRange - contentHeight); 1366 if (scrollY < 0) { 1367 scrollRange -= scrollY; 1368 } else if (scrollY > overscrollBottom) { 1369 scrollRange += scrollY - overscrollBottom; 1370 } 1371 1372 return scrollRange; 1373 } 1374 1375 @Override computeVerticalScrollOffset()1376 protected int computeVerticalScrollOffset() { 1377 return Math.max(0, super.computeVerticalScrollOffset()); 1378 } 1379 1380 @Override measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec)1381 protected void measureChild(View child, int parentWidthMeasureSpec, 1382 int parentHeightMeasureSpec) { 1383 ViewGroup.LayoutParams lp = child.getLayoutParams(); 1384 1385 int childWidthMeasureSpec; 1386 int childHeightMeasureSpec; 1387 1388 childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft 1389 + mPaddingRight, lp.width); 1390 final int verticalPadding = mPaddingTop + mPaddingBottom; 1391 childHeightMeasureSpec = MeasureSpec.makeSafeMeasureSpec( 1392 Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - verticalPadding), 1393 MeasureSpec.UNSPECIFIED); 1394 1395 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1396 } 1397 1398 @Override measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)1399 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 1400 int parentHeightMeasureSpec, int heightUsed) { 1401 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 1402 1403 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 1404 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 1405 + widthUsed, lp.width); 1406 final int usedTotal = mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin + 1407 heightUsed; 1408 final int childHeightMeasureSpec = MeasureSpec.makeSafeMeasureSpec( 1409 Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - usedTotal), 1410 MeasureSpec.UNSPECIFIED); 1411 1412 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1413 } 1414 1415 @Override computeScroll()1416 public void computeScroll() { 1417 if (mScroller.computeScrollOffset()) { 1418 // This is called at drawing time by ViewGroup. We don't want to 1419 // re-show the scrollbars at this point, which scrollTo will do, 1420 // so we replicate most of scrollTo here. 1421 // 1422 // It's a little odd to call onScrollChanged from inside the drawing. 1423 // 1424 // It is, except when you remember that computeScroll() is used to 1425 // animate scrolling. So unless we want to defer the onScrollChanged() 1426 // until the end of the animated scrolling, we don't really have a 1427 // choice here. 1428 // 1429 // I agree. The alternative, which I think would be worse, is to post 1430 // something and tell the subclasses later. This is bad because there 1431 // will be a window where mScrollX/Y is different from what the app 1432 // thinks it is. 1433 // 1434 int oldX = mScrollX; 1435 int oldY = mScrollY; 1436 int x = mScroller.getCurrX(); 1437 int y = mScroller.getCurrY(); 1438 1439 if (oldX != x || oldY != y) { 1440 final int range = getScrollRange(); 1441 final int overscrollMode = getOverScrollMode(); 1442 final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS || 1443 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); 1444 1445 overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, range, 1446 0, mOverflingDistance, false); 1447 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 1448 1449 if (canOverscroll) { 1450 if (y < 0 && oldY >= 0) { 1451 mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity()); 1452 } else if (y > range && oldY <= range) { 1453 mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity()); 1454 } 1455 } 1456 } 1457 1458 if (!awakenScrollBars()) { 1459 // Keep on drawing until the animation has finished. 1460 postInvalidateOnAnimation(); 1461 } 1462 } else { 1463 if (mFlingStrictSpan != null) { 1464 mFlingStrictSpan.finish(); 1465 mFlingStrictSpan = null; 1466 } 1467 } 1468 } 1469 1470 /** 1471 * Scrolls the view to the given child. 1472 * 1473 * @param child the View to scroll to 1474 */ scrollToDescendant(@onNull View child)1475 public void scrollToDescendant(@NonNull View child) { 1476 if (!mIsLayoutDirty) { 1477 child.getDrawingRect(mTempRect); 1478 1479 /* Offset from child's local coordinates to ScrollView coordinates */ 1480 offsetDescendantRectToMyCoords(child, mTempRect); 1481 1482 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1483 1484 if (scrollDelta != 0) { 1485 scrollBy(0, scrollDelta); 1486 } 1487 } else { 1488 mChildToScrollTo = child; 1489 } 1490 } 1491 1492 /** 1493 * If rect is off screen, scroll just enough to get it (or at least the 1494 * first screen size chunk of it) on screen. 1495 * 1496 * @param rect The rectangle. 1497 * @param immediate True to scroll immediately without animation 1498 * @return true if scrolling was performed 1499 */ scrollToChildRect(Rect rect, boolean immediate)1500 private boolean scrollToChildRect(Rect rect, boolean immediate) { 1501 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); 1502 final boolean scroll = delta != 0; 1503 if (scroll) { 1504 if (immediate) { 1505 scrollBy(0, delta); 1506 } else { 1507 smoothScrollBy(0, delta); 1508 } 1509 } 1510 return scroll; 1511 } 1512 1513 /** 1514 * Compute the amount to scroll in the Y direction in order to get 1515 * a rectangle completely on the screen (or, if taller than the screen, 1516 * at least the first screen size chunk of it). 1517 * 1518 * @param rect The rect. 1519 * @return The scroll delta. 1520 */ computeScrollDeltaToGetChildRectOnScreen(Rect rect)1521 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { 1522 if (getChildCount() == 0) return 0; 1523 1524 int height = getHeight(); 1525 int screenTop = getScrollY(); 1526 int screenBottom = screenTop + height; 1527 1528 int fadingEdge = getVerticalFadingEdgeLength(); 1529 1530 // leave room for top fading edge as long as rect isn't at very top 1531 if (rect.top > 0) { 1532 screenTop += fadingEdge; 1533 } 1534 1535 // leave room for bottom fading edge as long as rect isn't at very bottom 1536 if (rect.bottom < getChildAt(0).getHeight()) { 1537 screenBottom -= fadingEdge; 1538 } 1539 1540 int scrollYDelta = 0; 1541 1542 if (rect.bottom > screenBottom && rect.top > screenTop) { 1543 // need to move down to get it in view: move down just enough so 1544 // that the entire rectangle is in view (or at least the first 1545 // screen size chunk). 1546 1547 if (rect.height() > height) { 1548 // just enough to get screen size chunk on 1549 scrollYDelta += (rect.top - screenTop); 1550 } else { 1551 // get entire rect at bottom of screen 1552 scrollYDelta += (rect.bottom - screenBottom); 1553 } 1554 1555 // make sure we aren't scrolling beyond the end of our content 1556 int bottom = getChildAt(0).getBottom(); 1557 int distanceToBottom = bottom - screenBottom; 1558 scrollYDelta = Math.min(scrollYDelta, distanceToBottom); 1559 1560 } else if (rect.top < screenTop && rect.bottom < screenBottom) { 1561 // need to move up to get it in view: move up just enough so that 1562 // entire rectangle is in view (or at least the first screen 1563 // size chunk of it). 1564 1565 if (rect.height() > height) { 1566 // screen size chunk 1567 scrollYDelta -= (screenBottom - rect.bottom); 1568 } else { 1569 // entire rect at top 1570 scrollYDelta -= (screenTop - rect.top); 1571 } 1572 1573 // make sure we aren't scrolling any further than the top our content 1574 scrollYDelta = Math.max(scrollYDelta, -getScrollY()); 1575 } 1576 return scrollYDelta; 1577 } 1578 1579 @Override requestChildFocus(View child, View focused)1580 public void requestChildFocus(View child, View focused) { 1581 if (focused != null && focused.getRevealOnFocusHint()) { 1582 if (!mIsLayoutDirty) { 1583 scrollToDescendant(focused); 1584 } else { 1585 // The child may not be laid out yet, we can't compute the scroll yet 1586 mChildToScrollTo = focused; 1587 } 1588 } 1589 super.requestChildFocus(child, focused); 1590 } 1591 1592 1593 /** 1594 * When looking for focus in children of a scroll view, need to be a little 1595 * more careful not to give focus to something that is scrolled off screen. 1596 * 1597 * This is more expensive than the default {@link android.view.ViewGroup} 1598 * implementation, otherwise this behavior might have been made the default. 1599 */ 1600 @Override onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)1601 protected boolean onRequestFocusInDescendants(int direction, 1602 Rect previouslyFocusedRect) { 1603 1604 // convert from forward / backward notation to up / down / left / right 1605 // (ugh). 1606 if (direction == View.FOCUS_FORWARD) { 1607 direction = View.FOCUS_DOWN; 1608 } else if (direction == View.FOCUS_BACKWARD) { 1609 direction = View.FOCUS_UP; 1610 } 1611 1612 final View nextFocus = previouslyFocusedRect == null ? 1613 FocusFinder.getInstance().findNextFocus(this, null, direction) : 1614 FocusFinder.getInstance().findNextFocusFromRect(this, 1615 previouslyFocusedRect, direction); 1616 1617 if (nextFocus == null) { 1618 return false; 1619 } 1620 1621 if (isOffScreen(nextFocus)) { 1622 return false; 1623 } 1624 1625 return nextFocus.requestFocus(direction, previouslyFocusedRect); 1626 } 1627 1628 @Override requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate)1629 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 1630 boolean immediate) { 1631 // offset into coordinate space of this scroll view 1632 rectangle.offset(child.getLeft() - child.getScrollX(), 1633 child.getTop() - child.getScrollY()); 1634 1635 return scrollToChildRect(rectangle, immediate); 1636 } 1637 1638 @Override requestLayout()1639 public void requestLayout() { 1640 mIsLayoutDirty = true; 1641 super.requestLayout(); 1642 } 1643 1644 @Override onDetachedFromWindow()1645 protected void onDetachedFromWindow() { 1646 super.onDetachedFromWindow(); 1647 1648 if (mScrollStrictSpan != null) { 1649 mScrollStrictSpan.finish(); 1650 mScrollStrictSpan = null; 1651 } 1652 if (mFlingStrictSpan != null) { 1653 mFlingStrictSpan.finish(); 1654 mFlingStrictSpan = null; 1655 } 1656 } 1657 1658 @Override onLayout(boolean changed, int l, int t, int r, int b)1659 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1660 super.onLayout(changed, l, t, r, b); 1661 mIsLayoutDirty = false; 1662 // Give a child focus if it needs it 1663 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { 1664 scrollToDescendant(mChildToScrollTo); 1665 } 1666 mChildToScrollTo = null; 1667 1668 if (!isLaidOut()) { 1669 if (mSavedState != null) { 1670 mScrollY = mSavedState.scrollPosition; 1671 mSavedState = null; 1672 } // mScrollY default value is "0" 1673 1674 final int childHeight = (getChildCount() > 0) ? getChildAt(0).getMeasuredHeight() : 0; 1675 final int scrollRange = Math.max(0, 1676 childHeight - (b - t - mPaddingBottom - mPaddingTop)); 1677 1678 // Don't forget to clamp 1679 if (mScrollY > scrollRange) { 1680 mScrollY = scrollRange; 1681 } else if (mScrollY < 0) { 1682 mScrollY = 0; 1683 } 1684 } 1685 1686 // Calling this with the present values causes it to re-claim them 1687 scrollTo(mScrollX, mScrollY); 1688 } 1689 1690 @Override onSizeChanged(int w, int h, int oldw, int oldh)1691 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1692 super.onSizeChanged(w, h, oldw, oldh); 1693 1694 View currentFocused = findFocus(); 1695 if (null == currentFocused || this == currentFocused) 1696 return; 1697 1698 // If the currently-focused view was visible on the screen when the 1699 // screen was at the old height, then scroll the screen to make that 1700 // view visible with the new screen height. 1701 if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) { 1702 currentFocused.getDrawingRect(mTempRect); 1703 offsetDescendantRectToMyCoords(currentFocused, mTempRect); 1704 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1705 doScrollY(scrollDelta); 1706 } 1707 } 1708 1709 /** 1710 * Return true if child is a descendant of parent, (or equal to the parent). 1711 */ isViewDescendantOf(View child, View parent)1712 private static boolean isViewDescendantOf(View child, View parent) { 1713 if (child == parent) { 1714 return true; 1715 } 1716 1717 final ViewParent theParent = child.getParent(); 1718 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 1719 } 1720 1721 /** 1722 * Fling the scroll view 1723 * 1724 * @param velocityY The initial velocity in the Y direction. Positive 1725 * numbers mean that the finger/cursor is moving down the screen, 1726 * which means we want to scroll towards the top. 1727 */ fling(int velocityY)1728 public void fling(int velocityY) { 1729 if (getChildCount() > 0) { 1730 int height = getHeight() - mPaddingBottom - mPaddingTop; 1731 int bottom = getChildAt(0).getHeight(); 1732 1733 mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0, 1734 Math.max(0, bottom - height), 0, height/2); 1735 1736 if (mFlingStrictSpan == null) { 1737 mFlingStrictSpan = StrictMode.enterCriticalSpan("ScrollView-fling"); 1738 } 1739 1740 postInvalidateOnAnimation(); 1741 } 1742 } 1743 flingWithNestedDispatch(int velocityY)1744 private void flingWithNestedDispatch(int velocityY) { 1745 final boolean canFling = (mScrollY > 0 || velocityY > 0) && 1746 (mScrollY < getScrollRange() || velocityY < 0); 1747 if (!dispatchNestedPreFling(0, velocityY)) { 1748 dispatchNestedFling(0, velocityY, canFling); 1749 if (canFling) { 1750 fling(velocityY); 1751 } 1752 } 1753 } 1754 1755 @UnsupportedAppUsage endDrag()1756 private void endDrag() { 1757 mIsBeingDragged = false; 1758 1759 recycleVelocityTracker(); 1760 1761 if (shouldDisplayEdgeEffects()) { 1762 mEdgeGlowTop.onRelease(); 1763 mEdgeGlowBottom.onRelease(); 1764 } 1765 1766 if (mScrollStrictSpan != null) { 1767 mScrollStrictSpan.finish(); 1768 mScrollStrictSpan = null; 1769 } 1770 } 1771 1772 /** 1773 * {@inheritDoc} 1774 * 1775 * <p>This version also clamps the scrolling to the bounds of our child. 1776 */ 1777 @Override scrollTo(int x, int y)1778 public void scrollTo(int x, int y) { 1779 // we rely on the fact the View.scrollBy calls scrollTo. 1780 if (getChildCount() > 0) { 1781 View child = getChildAt(0); 1782 x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); 1783 y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); 1784 if (x != mScrollX || y != mScrollY) { 1785 super.scrollTo(x, y); 1786 } 1787 } 1788 } 1789 1790 @Override onStartNestedScroll(View child, View target, int nestedScrollAxes)1791 public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { 1792 return (nestedScrollAxes & SCROLL_AXIS_VERTICAL) != 0; 1793 } 1794 1795 @Override onNestedScrollAccepted(View child, View target, int axes)1796 public void onNestedScrollAccepted(View child, View target, int axes) { 1797 super.onNestedScrollAccepted(child, target, axes); 1798 startNestedScroll(SCROLL_AXIS_VERTICAL); 1799 } 1800 1801 /** 1802 * @inheritDoc 1803 */ 1804 @Override onStopNestedScroll(View target)1805 public void onStopNestedScroll(View target) { 1806 super.onStopNestedScroll(target); 1807 } 1808 1809 @Override onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed)1810 public void onNestedScroll(View target, int dxConsumed, int dyConsumed, 1811 int dxUnconsumed, int dyUnconsumed) { 1812 final int oldScrollY = mScrollY; 1813 scrollBy(0, dyUnconsumed); 1814 final int myConsumed = mScrollY - oldScrollY; 1815 final int myUnconsumed = dyUnconsumed - myConsumed; 1816 dispatchNestedScroll(0, myConsumed, 0, myUnconsumed, null); 1817 } 1818 1819 /** 1820 * @inheritDoc 1821 */ 1822 @Override onNestedFling(View target, float velocityX, float velocityY, boolean consumed)1823 public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { 1824 if (!consumed) { 1825 flingWithNestedDispatch((int) velocityY); 1826 return true; 1827 } 1828 return false; 1829 } 1830 1831 @Override draw(Canvas canvas)1832 public void draw(Canvas canvas) { 1833 super.draw(canvas); 1834 if (shouldDisplayEdgeEffects()) { 1835 final int scrollY = mScrollY; 1836 final boolean clipToPadding = getClipToPadding(); 1837 if (!mEdgeGlowTop.isFinished()) { 1838 final int restoreCount = canvas.save(); 1839 final int width; 1840 final int height; 1841 final float translateX; 1842 final float translateY; 1843 if (clipToPadding) { 1844 width = getWidth() - mPaddingLeft - mPaddingRight; 1845 height = getHeight() - mPaddingTop - mPaddingBottom; 1846 translateX = mPaddingLeft; 1847 translateY = mPaddingTop; 1848 } else { 1849 width = getWidth(); 1850 height = getHeight(); 1851 translateX = 0; 1852 translateY = 0; 1853 } 1854 canvas.translate(translateX, Math.min(0, scrollY) + translateY); 1855 mEdgeGlowTop.setSize(width, height); 1856 if (mEdgeGlowTop.draw(canvas)) { 1857 postInvalidateOnAnimation(); 1858 } 1859 canvas.restoreToCount(restoreCount); 1860 } 1861 if (!mEdgeGlowBottom.isFinished()) { 1862 final int restoreCount = canvas.save(); 1863 final int width; 1864 final int height; 1865 final float translateX; 1866 final float translateY; 1867 if (clipToPadding) { 1868 width = getWidth() - mPaddingLeft - mPaddingRight; 1869 height = getHeight() - mPaddingTop - mPaddingBottom; 1870 translateX = mPaddingLeft; 1871 translateY = mPaddingTop; 1872 } else { 1873 width = getWidth(); 1874 height = getHeight(); 1875 translateX = 0; 1876 translateY = 0; 1877 } 1878 canvas.translate(-width + translateX, 1879 Math.max(getScrollRange(), scrollY) + height + translateY); 1880 canvas.rotate(180, width, 0); 1881 mEdgeGlowBottom.setSize(width, height); 1882 if (mEdgeGlowBottom.draw(canvas)) { 1883 postInvalidateOnAnimation(); 1884 } 1885 canvas.restoreToCount(restoreCount); 1886 } 1887 } 1888 } 1889 clamp(int n, int my, int child)1890 private static int clamp(int n, int my, int child) { 1891 if (my >= child || n < 0) { 1892 /* my >= child is this case: 1893 * |--------------- me ---------------| 1894 * |------ child ------| 1895 * or 1896 * |--------------- me ---------------| 1897 * |------ child ------| 1898 * or 1899 * |--------------- me ---------------| 1900 * |------ child ------| 1901 * 1902 * n < 0 is this case: 1903 * |------ me ------| 1904 * |-------- child --------| 1905 * |-- mScrollX --| 1906 */ 1907 return 0; 1908 } 1909 if ((my+n) > child) { 1910 /* this case: 1911 * |------ me ------| 1912 * |------ child ------| 1913 * |-- mScrollX --| 1914 */ 1915 return child-my; 1916 } 1917 return n; 1918 } 1919 1920 @Override onRestoreInstanceState(Parcelable state)1921 protected void onRestoreInstanceState(Parcelable state) { 1922 if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) { 1923 // Some old apps reused IDs in ways they shouldn't have. 1924 // Don't break them, but they don't get scroll state restoration. 1925 super.onRestoreInstanceState(state); 1926 return; 1927 } 1928 SavedState ss = (SavedState) state; 1929 super.onRestoreInstanceState(ss.getSuperState()); 1930 mSavedState = ss; 1931 requestLayout(); 1932 } 1933 1934 @Override onSaveInstanceState()1935 protected Parcelable onSaveInstanceState() { 1936 if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) { 1937 // Some old apps reused IDs in ways they shouldn't have. 1938 // Don't break them, but they don't get scroll state restoration. 1939 return super.onSaveInstanceState(); 1940 } 1941 Parcelable superState = super.onSaveInstanceState(); 1942 SavedState ss = new SavedState(superState); 1943 ss.scrollPosition = mScrollY; 1944 return ss; 1945 } 1946 1947 /** @hide */ 1948 @Override encodeProperties(@onNull ViewHierarchyEncoder encoder)1949 protected void encodeProperties(@NonNull ViewHierarchyEncoder encoder) { 1950 super.encodeProperties(encoder); 1951 encoder.addProperty("fillViewport", mFillViewport); 1952 } 1953 1954 static class SavedState extends BaseSavedState { 1955 public int scrollPosition; 1956 SavedState(Parcelable superState)1957 SavedState(Parcelable superState) { 1958 super(superState); 1959 } 1960 SavedState(Parcel source)1961 public SavedState(Parcel source) { 1962 super(source); 1963 scrollPosition = source.readInt(); 1964 } 1965 1966 @Override writeToParcel(Parcel dest, int flags)1967 public void writeToParcel(Parcel dest, int flags) { 1968 super.writeToParcel(dest, flags); 1969 dest.writeInt(scrollPosition); 1970 } 1971 1972 @Override toString()1973 public String toString() { 1974 return "ScrollView.SavedState{" 1975 + Integer.toHexString(System.identityHashCode(this)) 1976 + " scrollPosition=" + scrollPosition + "}"; 1977 } 1978 1979 public static final @android.annotation.NonNull Parcelable.Creator<SavedState> CREATOR 1980 = new Parcelable.Creator<SavedState>() { 1981 public SavedState createFromParcel(Parcel in) { 1982 return new SavedState(in); 1983 } 1984 1985 public SavedState[] newArray(int size) { 1986 return new SavedState[size]; 1987 } 1988 }; 1989 } 1990 1991 } 1992