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