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