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