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