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 android.content.Context; 21import android.content.res.TypedArray; 22import android.graphics.Canvas; 23import android.graphics.Rect; 24import android.os.Bundle; 25import android.os.Parcel; 26import android.os.Parcelable; 27import android.support.annotation.RestrictTo; 28import android.support.v4.view.AccessibilityDelegateCompat; 29import android.support.v4.view.InputDeviceCompat; 30import android.support.v4.view.MotionEventCompat; 31import android.support.v4.view.NestedScrollingChild; 32import android.support.v4.view.NestedScrollingChildHelper; 33import android.support.v4.view.NestedScrollingParent; 34import android.support.v4.view.NestedScrollingParentHelper; 35import android.support.v4.view.ScrollingView; 36import android.support.v4.view.VelocityTrackerCompat; 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.FrameLayout; 55import android.widget.ScrollView; 56 57import java.util.List; 58 59import static android.support.annotation.RestrictTo.Scope.GROUP_ID; 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 ScrollerCompat mScroller; 100 private EdgeEffectCompat mEdgeGlowTop; 101 private EdgeEffectCompat 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 = ScrollerCompat.create(getContext(), null); 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 & MotionEventCompat.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 MotionEventCompat.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 = MotionEventCompat.getActionMasked(ev); 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 mEdgeGlowTop.onPull((float) deltaY / getHeight(), 814 ev.getX(activePointerIndex) / getWidth()); 815 if (!mEdgeGlowBottom.isFinished()) { 816 mEdgeGlowBottom.onRelease(); 817 } 818 } else if (pulledToY > range) { 819 mEdgeGlowBottom.onPull((float) deltaY / getHeight(), 820 1.f - ev.getX(activePointerIndex) 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) VelocityTrackerCompat.getYVelocity(velocityTracker, 838 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 MotionEventCompat.ACTION_POINTER_DOWN: { 861 final int index = MotionEventCompat.getActionIndex(ev); 862 mLastMotionY = (int) ev.getY(index); 863 mActivePointerId = ev.getPointerId(index); 864 break; 865 } 866 case MotionEventCompat.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.getAction() & MotionEventCompat.ACTION_POINTER_INDEX_MASK) 881 >> MotionEventCompat.ACTION_POINTER_INDEX_SHIFT; 882 final int pointerId = ev.getPointerId(pointerIndex); 883 if (pointerId == mActivePointerId) { 884 // This was our active pointer going up. Choose a new 885 // active pointer and adjust accordingly. 886 // TODO: Make this decision more intelligent. 887 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 888 mLastMotionY = (int) ev.getY(newPointerIndex); 889 mActivePointerId = ev.getPointerId(newPointerIndex); 890 if (mVelocityTracker != null) { 891 mVelocityTracker.clear(); 892 } 893 } 894 } 895 896 public boolean onGenericMotionEvent(MotionEvent event) { 897 if ((event.getSource() & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) { 898 switch (event.getAction()) { 899 case MotionEventCompat.ACTION_SCROLL: { 900 if (!mIsBeingDragged) { 901 final float vscroll = MotionEventCompat.getAxisValue(event, 902 MotionEventCompat.AXIS_VSCROLL); 903 if (vscroll != 0) { 904 final int delta = (int) (vscroll * getVerticalScrollFactorCompat()); 905 final int range = getScrollRange(); 906 int oldScrollY = getScrollY(); 907 int newScrollY = oldScrollY - delta; 908 if (newScrollY < 0) { 909 newScrollY = 0; 910 } else if (newScrollY > range) { 911 newScrollY = range; 912 } 913 if (newScrollY != oldScrollY) { 914 super.scrollTo(getScrollX(), newScrollY); 915 return true; 916 } 917 } 918 } 919 } 920 } 921 } 922 return false; 923 } 924 925 private float getVerticalScrollFactorCompat() { 926 if (mVerticalScrollFactor == 0) { 927 TypedValue outValue = new TypedValue(); 928 final Context context = getContext(); 929 if (!context.getTheme().resolveAttribute( 930 android.R.attr.listPreferredItemHeight, outValue, true)) { 931 throw new IllegalStateException( 932 "Expected theme to define listPreferredItemHeight."); 933 } 934 mVerticalScrollFactor = outValue.getDimension( 935 context.getResources().getDisplayMetrics()); 936 } 937 return mVerticalScrollFactor; 938 } 939 940 @Override 941 protected void onOverScrolled(int scrollX, int scrollY, 942 boolean clampedX, boolean clampedY) { 943 super.scrollTo(scrollX, scrollY); 944 } 945 946 boolean overScrollByCompat(int deltaX, int deltaY, 947 int scrollX, int scrollY, 948 int scrollRangeX, int scrollRangeY, 949 int maxOverScrollX, int maxOverScrollY, 950 boolean isTouchEvent) { 951 final int overScrollMode = getOverScrollMode(); 952 final boolean canScrollHorizontal = 953 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 954 final boolean canScrollVertical = 955 computeVerticalScrollRange() > computeVerticalScrollExtent(); 956 final boolean overScrollHorizontal = overScrollMode == View.OVER_SCROLL_ALWAYS 957 || (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 958 final boolean overScrollVertical = overScrollMode == View.OVER_SCROLL_ALWAYS 959 || (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 960 961 int newScrollX = scrollX + deltaX; 962 if (!overScrollHorizontal) { 963 maxOverScrollX = 0; 964 } 965 966 int newScrollY = scrollY + deltaY; 967 if (!overScrollVertical) { 968 maxOverScrollY = 0; 969 } 970 971 // Clamp values if at the limits and record 972 final int left = -maxOverScrollX; 973 final int right = maxOverScrollX + scrollRangeX; 974 final int top = -maxOverScrollY; 975 final int bottom = maxOverScrollY + scrollRangeY; 976 977 boolean clampedX = false; 978 if (newScrollX > right) { 979 newScrollX = right; 980 clampedX = true; 981 } else if (newScrollX < left) { 982 newScrollX = left; 983 clampedX = true; 984 } 985 986 boolean clampedY = false; 987 if (newScrollY > bottom) { 988 newScrollY = bottom; 989 clampedY = true; 990 } else if (newScrollY < top) { 991 newScrollY = top; 992 clampedY = true; 993 } 994 995 if (clampedY) { 996 mScroller.springBack(newScrollX, newScrollY, 0, 0, 0, getScrollRange()); 997 } 998 999 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 1000 1001 return clampedX || clampedY; 1002 } 1003 1004 int getScrollRange() { 1005 int scrollRange = 0; 1006 if (getChildCount() > 0) { 1007 View child = getChildAt(0); 1008 scrollRange = Math.max(0, 1009 child.getHeight() - (getHeight() - getPaddingBottom() - getPaddingTop())); 1010 } 1011 return scrollRange; 1012 } 1013 1014 /** 1015 * <p> 1016 * Finds the next focusable component that fits in the specified bounds. 1017 * </p> 1018 * 1019 * @param topFocus look for a candidate is the one at the top of the bounds 1020 * if topFocus is true, or at the bottom of the bounds if topFocus is 1021 * false 1022 * @param top the top offset of the bounds in which a focusable must be 1023 * found 1024 * @param bottom the bottom offset of the bounds in which a focusable must 1025 * be found 1026 * @return the next focusable component in the bounds or null if none can 1027 * be found 1028 */ 1029 private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) { 1030 1031 List<View> focusables = getFocusables(View.FOCUS_FORWARD); 1032 View focusCandidate = null; 1033 1034 /* 1035 * A fully contained focusable is one where its top is below the bound's 1036 * top, and its bottom is above the bound's bottom. A partially 1037 * contained focusable is one where some part of it is within the 1038 * bounds, but it also has some part that is not within bounds. A fully contained 1039 * focusable is preferred to a partially contained focusable. 1040 */ 1041 boolean foundFullyContainedFocusable = false; 1042 1043 int count = focusables.size(); 1044 for (int i = 0; i < count; i++) { 1045 View view = focusables.get(i); 1046 int viewTop = view.getTop(); 1047 int viewBottom = view.getBottom(); 1048 1049 if (top < viewBottom && viewTop < bottom) { 1050 /* 1051 * the focusable is in the target area, it is a candidate for 1052 * focusing 1053 */ 1054 1055 final boolean viewIsFullyContained = (top < viewTop) && (viewBottom < bottom); 1056 1057 if (focusCandidate == null) { 1058 /* No candidate, take this one */ 1059 focusCandidate = view; 1060 foundFullyContainedFocusable = viewIsFullyContained; 1061 } else { 1062 final boolean viewIsCloserToBoundary = 1063 (topFocus && viewTop < focusCandidate.getTop()) 1064 || (!topFocus && viewBottom > focusCandidate.getBottom()); 1065 1066 if (foundFullyContainedFocusable) { 1067 if (viewIsFullyContained && viewIsCloserToBoundary) { 1068 /* 1069 * We're dealing with only fully contained views, so 1070 * it has to be closer to the boundary to beat our 1071 * candidate 1072 */ 1073 focusCandidate = view; 1074 } 1075 } else { 1076 if (viewIsFullyContained) { 1077 /* Any fully contained view beats a partially contained view */ 1078 focusCandidate = view; 1079 foundFullyContainedFocusable = true; 1080 } else if (viewIsCloserToBoundary) { 1081 /* 1082 * Partially contained view beats another partially 1083 * contained view if it's closer 1084 */ 1085 focusCandidate = view; 1086 } 1087 } 1088 } 1089 } 1090 } 1091 1092 return focusCandidate; 1093 } 1094 1095 /** 1096 * <p>Handles scrolling in response to a "page up/down" shortcut press. This 1097 * method will scroll the view by one page up or down and give the focus 1098 * to the topmost/bottommost component in the new visible area. If no 1099 * component is a good candidate for focus, this scrollview reclaims the 1100 * focus.</p> 1101 * 1102 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 1103 * to go one page up or 1104 * {@link android.view.View#FOCUS_DOWN} to go one page down 1105 * @return true if the key event is consumed by this method, false otherwise 1106 */ 1107 public boolean pageScroll(int direction) { 1108 boolean down = direction == View.FOCUS_DOWN; 1109 int height = getHeight(); 1110 1111 if (down) { 1112 mTempRect.top = getScrollY() + height; 1113 int count = getChildCount(); 1114 if (count > 0) { 1115 View view = getChildAt(count - 1); 1116 if (mTempRect.top + height > view.getBottom()) { 1117 mTempRect.top = view.getBottom() - height; 1118 } 1119 } 1120 } else { 1121 mTempRect.top = getScrollY() - height; 1122 if (mTempRect.top < 0) { 1123 mTempRect.top = 0; 1124 } 1125 } 1126 mTempRect.bottom = mTempRect.top + height; 1127 1128 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 1129 } 1130 1131 /** 1132 * <p>Handles scrolling in response to a "home/end" shortcut press. This 1133 * method will scroll the view to the top or bottom and give the focus 1134 * to the topmost/bottommost component in the new visible area. If no 1135 * component is a good candidate for focus, this scrollview reclaims the 1136 * focus.</p> 1137 * 1138 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 1139 * to go the top of the view or 1140 * {@link android.view.View#FOCUS_DOWN} to go the bottom 1141 * @return true if the key event is consumed by this method, false otherwise 1142 */ 1143 public boolean fullScroll(int direction) { 1144 boolean down = direction == View.FOCUS_DOWN; 1145 int height = getHeight(); 1146 1147 mTempRect.top = 0; 1148 mTempRect.bottom = height; 1149 1150 if (down) { 1151 int count = getChildCount(); 1152 if (count > 0) { 1153 View view = getChildAt(count - 1); 1154 mTempRect.bottom = view.getBottom() + getPaddingBottom(); 1155 mTempRect.top = mTempRect.bottom - height; 1156 } 1157 } 1158 1159 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 1160 } 1161 1162 /** 1163 * <p>Scrolls the view to make the area defined by <code>top</code> and 1164 * <code>bottom</code> visible. This method attempts to give the focus 1165 * to a component visible in this area. If no component can be focused in 1166 * the new visible area, the focus is reclaimed by this ScrollView.</p> 1167 * 1168 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 1169 * to go upward, {@link android.view.View#FOCUS_DOWN} to downward 1170 * @param top the top offset of the new area to be made visible 1171 * @param bottom the bottom offset of the new area to be made visible 1172 * @return true if the key event is consumed by this method, false otherwise 1173 */ 1174 private boolean scrollAndFocus(int direction, int top, int bottom) { 1175 boolean handled = true; 1176 1177 int height = getHeight(); 1178 int containerTop = getScrollY(); 1179 int containerBottom = containerTop + height; 1180 boolean up = direction == View.FOCUS_UP; 1181 1182 View newFocused = findFocusableViewInBounds(up, top, bottom); 1183 if (newFocused == null) { 1184 newFocused = this; 1185 } 1186 1187 if (top >= containerTop && bottom <= containerBottom) { 1188 handled = false; 1189 } else { 1190 int delta = up ? (top - containerTop) : (bottom - containerBottom); 1191 doScrollY(delta); 1192 } 1193 1194 if (newFocused != findFocus()) newFocused.requestFocus(direction); 1195 1196 return handled; 1197 } 1198 1199 /** 1200 * Handle scrolling in response to an up or down arrow click. 1201 * 1202 * @param direction The direction corresponding to the arrow key that was 1203 * pressed 1204 * @return True if we consumed the event, false otherwise 1205 */ 1206 public boolean arrowScroll(int direction) { 1207 1208 View currentFocused = findFocus(); 1209 if (currentFocused == this) currentFocused = null; 1210 1211 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); 1212 1213 final int maxJump = getMaxScrollAmount(); 1214 1215 if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) { 1216 nextFocused.getDrawingRect(mTempRect); 1217 offsetDescendantRectToMyCoords(nextFocused, mTempRect); 1218 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1219 doScrollY(scrollDelta); 1220 nextFocused.requestFocus(direction); 1221 } else { 1222 // no new focus 1223 int scrollDelta = maxJump; 1224 1225 if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { 1226 scrollDelta = getScrollY(); 1227 } else if (direction == View.FOCUS_DOWN) { 1228 if (getChildCount() > 0) { 1229 int daBottom = getChildAt(0).getBottom(); 1230 int screenBottom = getScrollY() + getHeight() - getPaddingBottom(); 1231 if (daBottom - screenBottom < maxJump) { 1232 scrollDelta = daBottom - screenBottom; 1233 } 1234 } 1235 } 1236 if (scrollDelta == 0) { 1237 return false; 1238 } 1239 doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); 1240 } 1241 1242 if (currentFocused != null && currentFocused.isFocused() 1243 && isOffScreen(currentFocused)) { 1244 // previously focused item still has focus and is off screen, give 1245 // it up (take it back to ourselves) 1246 // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are 1247 // sure to 1248 // get it) 1249 final int descendantFocusability = getDescendantFocusability(); // save 1250 setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); 1251 requestFocus(); 1252 setDescendantFocusability(descendantFocusability); // restore 1253 } 1254 return true; 1255 } 1256 1257 /** 1258 * @return whether the descendant of this scroll view is scrolled off 1259 * screen. 1260 */ 1261 private boolean isOffScreen(View descendant) { 1262 return !isWithinDeltaOfScreen(descendant, 0, getHeight()); 1263 } 1264 1265 /** 1266 * @return whether the descendant of this scroll view is within delta 1267 * pixels of being on the screen. 1268 */ 1269 private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) { 1270 descendant.getDrawingRect(mTempRect); 1271 offsetDescendantRectToMyCoords(descendant, mTempRect); 1272 1273 return (mTempRect.bottom + delta) >= getScrollY() 1274 && (mTempRect.top - delta) <= (getScrollY() + height); 1275 } 1276 1277 /** 1278 * Smooth scroll by a Y delta 1279 * 1280 * @param delta the number of pixels to scroll by on the Y axis 1281 */ 1282 private void doScrollY(int delta) { 1283 if (delta != 0) { 1284 if (mSmoothScrollingEnabled) { 1285 smoothScrollBy(0, delta); 1286 } else { 1287 scrollBy(0, delta); 1288 } 1289 } 1290 } 1291 1292 /** 1293 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 1294 * 1295 * @param dx the number of pixels to scroll by on the X axis 1296 * @param dy the number of pixels to scroll by on the Y axis 1297 */ 1298 public final void smoothScrollBy(int dx, int dy) { 1299 if (getChildCount() == 0) { 1300 // Nothing to do. 1301 return; 1302 } 1303 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 1304 if (duration > ANIMATED_SCROLL_GAP) { 1305 final int height = getHeight() - getPaddingBottom() - getPaddingTop(); 1306 final int bottom = getChildAt(0).getHeight(); 1307 final int maxY = Math.max(0, bottom - height); 1308 final int scrollY = getScrollY(); 1309 dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY; 1310 1311 mScroller.startScroll(getScrollX(), scrollY, 0, dy); 1312 ViewCompat.postInvalidateOnAnimation(this); 1313 } else { 1314 if (!mScroller.isFinished()) { 1315 mScroller.abortAnimation(); 1316 } 1317 scrollBy(dx, dy); 1318 } 1319 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 1320 } 1321 1322 /** 1323 * Like {@link #scrollTo}, but scroll smoothly instead of immediately. 1324 * 1325 * @param x the position where to scroll on the X axis 1326 * @param y the position where to scroll on the Y axis 1327 */ 1328 public final void smoothScrollTo(int x, int y) { 1329 smoothScrollBy(x - getScrollX(), y - getScrollY()); 1330 } 1331 1332 /** 1333 * <p>The scroll range of a scroll view is the overall height of all of its 1334 * children.</p> 1335 * @hide 1336 */ 1337 @RestrictTo(GROUP_ID) 1338 @Override 1339 public int computeVerticalScrollRange() { 1340 final int count = getChildCount(); 1341 final int contentHeight = getHeight() - getPaddingBottom() - getPaddingTop(); 1342 if (count == 0) { 1343 return contentHeight; 1344 } 1345 1346 int scrollRange = getChildAt(0).getBottom(); 1347 final int scrollY = getScrollY(); 1348 final int overscrollBottom = Math.max(0, scrollRange - contentHeight); 1349 if (scrollY < 0) { 1350 scrollRange -= scrollY; 1351 } else if (scrollY > overscrollBottom) { 1352 scrollRange += scrollY - overscrollBottom; 1353 } 1354 1355 return scrollRange; 1356 } 1357 1358 /** @hide */ 1359 @RestrictTo(GROUP_ID) 1360 @Override 1361 public int computeVerticalScrollOffset() { 1362 return Math.max(0, super.computeVerticalScrollOffset()); 1363 } 1364 1365 /** @hide */ 1366 @RestrictTo(GROUP_ID) 1367 @Override 1368 public int computeVerticalScrollExtent() { 1369 return super.computeVerticalScrollExtent(); 1370 } 1371 1372 /** @hide */ 1373 @RestrictTo(GROUP_ID) 1374 @Override 1375 public int computeHorizontalScrollRange() { 1376 return super.computeHorizontalScrollRange(); 1377 } 1378 1379 /** @hide */ 1380 @RestrictTo(GROUP_ID) 1381 @Override 1382 public int computeHorizontalScrollOffset() { 1383 return super.computeHorizontalScrollOffset(); 1384 } 1385 1386 /** @hide */ 1387 @RestrictTo(GROUP_ID) 1388 @Override 1389 public int computeHorizontalScrollExtent() { 1390 return super.computeHorizontalScrollExtent(); 1391 } 1392 1393 @Override 1394 protected void measureChild(View child, int parentWidthMeasureSpec, 1395 int parentHeightMeasureSpec) { 1396 ViewGroup.LayoutParams lp = child.getLayoutParams(); 1397 1398 int childWidthMeasureSpec; 1399 int childHeightMeasureSpec; 1400 1401 childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() 1402 + getPaddingRight(), lp.width); 1403 1404 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 1405 1406 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1407 } 1408 1409 @Override 1410 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 1411 int parentHeightMeasureSpec, int heightUsed) { 1412 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 1413 1414 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 1415 getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin 1416 + widthUsed, lp.width); 1417 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( 1418 lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED); 1419 1420 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1421 } 1422 1423 @Override 1424 public void computeScroll() { 1425 if (mScroller.computeScrollOffset()) { 1426 int oldX = getScrollX(); 1427 int oldY = getScrollY(); 1428 int x = mScroller.getCurrX(); 1429 int y = mScroller.getCurrY(); 1430 1431 if (oldX != x || oldY != y) { 1432 final int range = getScrollRange(); 1433 final int overscrollMode = getOverScrollMode(); 1434 final boolean canOverscroll = overscrollMode == View.OVER_SCROLL_ALWAYS 1435 || (overscrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); 1436 1437 overScrollByCompat(x - oldX, y - oldY, oldX, oldY, 0, range, 1438 0, 0, false); 1439 1440 if (canOverscroll) { 1441 ensureGlows(); 1442 if (y <= 0 && oldY > 0) { 1443 mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity()); 1444 } else if (y >= range && oldY < range) { 1445 mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity()); 1446 } 1447 } 1448 } 1449 } 1450 } 1451 1452 /** 1453 * Scrolls the view to the given child. 1454 * 1455 * @param child the View to scroll to 1456 */ 1457 private void scrollToChild(View child) { 1458 child.getDrawingRect(mTempRect); 1459 1460 /* Offset from child's local coordinates to ScrollView coordinates */ 1461 offsetDescendantRectToMyCoords(child, mTempRect); 1462 1463 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1464 1465 if (scrollDelta != 0) { 1466 scrollBy(0, scrollDelta); 1467 } 1468 } 1469 1470 /** 1471 * If rect is off screen, scroll just enough to get it (or at least the 1472 * first screen size chunk of it) on screen. 1473 * 1474 * @param rect The rectangle. 1475 * @param immediate True to scroll immediately without animation 1476 * @return true if scrolling was performed 1477 */ 1478 private boolean scrollToChildRect(Rect rect, boolean immediate) { 1479 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); 1480 final boolean scroll = delta != 0; 1481 if (scroll) { 1482 if (immediate) { 1483 scrollBy(0, delta); 1484 } else { 1485 smoothScrollBy(0, delta); 1486 } 1487 } 1488 return scroll; 1489 } 1490 1491 /** 1492 * Compute the amount to scroll in the Y direction in order to get 1493 * a rectangle completely on the screen (or, if taller than the screen, 1494 * at least the first screen size chunk of it). 1495 * 1496 * @param rect The rect. 1497 * @return The scroll delta. 1498 */ 1499 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { 1500 if (getChildCount() == 0) return 0; 1501 1502 int height = getHeight(); 1503 int screenTop = getScrollY(); 1504 int screenBottom = screenTop + height; 1505 1506 int fadingEdge = getVerticalFadingEdgeLength(); 1507 1508 // leave room for top fading edge as long as rect isn't at very top 1509 if (rect.top > 0) { 1510 screenTop += fadingEdge; 1511 } 1512 1513 // leave room for bottom fading edge as long as rect isn't at very bottom 1514 if (rect.bottom < getChildAt(0).getHeight()) { 1515 screenBottom -= fadingEdge; 1516 } 1517 1518 int scrollYDelta = 0; 1519 1520 if (rect.bottom > screenBottom && rect.top > screenTop) { 1521 // need to move down to get it in view: move down just enough so 1522 // that the entire rectangle is in view (or at least the first 1523 // screen size chunk). 1524 1525 if (rect.height() > height) { 1526 // just enough to get screen size chunk on 1527 scrollYDelta += (rect.top - screenTop); 1528 } else { 1529 // get entire rect at bottom of screen 1530 scrollYDelta += (rect.bottom - screenBottom); 1531 } 1532 1533 // make sure we aren't scrolling beyond the end of our content 1534 int bottom = getChildAt(0).getBottom(); 1535 int distanceToBottom = bottom - screenBottom; 1536 scrollYDelta = Math.min(scrollYDelta, distanceToBottom); 1537 1538 } else if (rect.top < screenTop && rect.bottom < screenBottom) { 1539 // need to move up to get it in view: move up just enough so that 1540 // entire rectangle is in view (or at least the first screen 1541 // size chunk of it). 1542 1543 if (rect.height() > height) { 1544 // screen size chunk 1545 scrollYDelta -= (screenBottom - rect.bottom); 1546 } else { 1547 // entire rect at top 1548 scrollYDelta -= (screenTop - rect.top); 1549 } 1550 1551 // make sure we aren't scrolling any further than the top our content 1552 scrollYDelta = Math.max(scrollYDelta, -getScrollY()); 1553 } 1554 return scrollYDelta; 1555 } 1556 1557 @Override 1558 public void requestChildFocus(View child, View focused) { 1559 if (!mIsLayoutDirty) { 1560 scrollToChild(focused); 1561 } else { 1562 // The child may not be laid out yet, we can't compute the scroll yet 1563 mChildToScrollTo = focused; 1564 } 1565 super.requestChildFocus(child, focused); 1566 } 1567 1568 1569 /** 1570 * When looking for focus in children of a scroll view, need to be a little 1571 * more careful not to give focus to something that is scrolled off screen. 1572 * 1573 * This is more expensive than the default {@link android.view.ViewGroup} 1574 * implementation, otherwise this behavior might have been made the default. 1575 */ 1576 @Override 1577 protected boolean onRequestFocusInDescendants(int direction, 1578 Rect previouslyFocusedRect) { 1579 1580 // convert from forward / backward notation to up / down / left / right 1581 // (ugh). 1582 if (direction == View.FOCUS_FORWARD) { 1583 direction = View.FOCUS_DOWN; 1584 } else if (direction == View.FOCUS_BACKWARD) { 1585 direction = View.FOCUS_UP; 1586 } 1587 1588 final View nextFocus = previouslyFocusedRect == null 1589 ? FocusFinder.getInstance().findNextFocus(this, null, direction) 1590 : FocusFinder.getInstance().findNextFocusFromRect( 1591 this, previouslyFocusedRect, direction); 1592 1593 if (nextFocus == null) { 1594 return false; 1595 } 1596 1597 if (isOffScreen(nextFocus)) { 1598 return false; 1599 } 1600 1601 return nextFocus.requestFocus(direction, previouslyFocusedRect); 1602 } 1603 1604 @Override 1605 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 1606 boolean immediate) { 1607 // offset into coordinate space of this scroll view 1608 rectangle.offset(child.getLeft() - child.getScrollX(), 1609 child.getTop() - child.getScrollY()); 1610 1611 return scrollToChildRect(rectangle, immediate); 1612 } 1613 1614 @Override 1615 public void requestLayout() { 1616 mIsLayoutDirty = true; 1617 super.requestLayout(); 1618 } 1619 1620 @Override 1621 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1622 super.onLayout(changed, l, t, r, b); 1623 mIsLayoutDirty = false; 1624 // Give a child focus if it needs it 1625 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { 1626 scrollToChild(mChildToScrollTo); 1627 } 1628 mChildToScrollTo = null; 1629 1630 if (!mIsLaidOut) { 1631 if (mSavedState != null) { 1632 scrollTo(getScrollX(), mSavedState.scrollPosition); 1633 mSavedState = null; 1634 } // mScrollY default value is "0" 1635 1636 final int childHeight = (getChildCount() > 0) ? getChildAt(0).getMeasuredHeight() : 0; 1637 final int scrollRange = Math.max(0, 1638 childHeight - (b - t - getPaddingBottom() - getPaddingTop())); 1639 1640 // Don't forget to clamp 1641 if (getScrollY() > scrollRange) { 1642 scrollTo(getScrollX(), scrollRange); 1643 } else if (getScrollY() < 0) { 1644 scrollTo(getScrollX(), 0); 1645 } 1646 } 1647 1648 // Calling this with the present values causes it to re-claim them 1649 scrollTo(getScrollX(), getScrollY()); 1650 mIsLaidOut = true; 1651 } 1652 1653 @Override 1654 public void onAttachedToWindow() { 1655 super.onAttachedToWindow(); 1656 1657 mIsLaidOut = false; 1658 } 1659 1660 @Override 1661 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1662 super.onSizeChanged(w, h, oldw, oldh); 1663 1664 View currentFocused = findFocus(); 1665 if (null == currentFocused || this == currentFocused) { 1666 return; 1667 } 1668 1669 // If the currently-focused view was visible on the screen when the 1670 // screen was at the old height, then scroll the screen to make that 1671 // view visible with the new screen height. 1672 if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) { 1673 currentFocused.getDrawingRect(mTempRect); 1674 offsetDescendantRectToMyCoords(currentFocused, mTempRect); 1675 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1676 doScrollY(scrollDelta); 1677 } 1678 } 1679 1680 /** 1681 * Return true if child is a descendant of parent, (or equal to the parent). 1682 */ 1683 private static boolean isViewDescendantOf(View child, View parent) { 1684 if (child == parent) { 1685 return true; 1686 } 1687 1688 final ViewParent theParent = child.getParent(); 1689 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 1690 } 1691 1692 /** 1693 * Fling the scroll view 1694 * 1695 * @param velocityY The initial velocity in the Y direction. Positive 1696 * numbers mean that the finger/cursor is moving down the screen, 1697 * which means we want to scroll towards the top. 1698 */ 1699 public void fling(int velocityY) { 1700 if (getChildCount() > 0) { 1701 int height = getHeight() - getPaddingBottom() - getPaddingTop(); 1702 int bottom = getChildAt(0).getHeight(); 1703 1704 mScroller.fling(getScrollX(), getScrollY(), 0, velocityY, 0, 0, 0, 1705 Math.max(0, bottom - height), 0, height / 2); 1706 1707 ViewCompat.postInvalidateOnAnimation(this); 1708 } 1709 } 1710 1711 private void flingWithNestedDispatch(int velocityY) { 1712 final int scrollY = getScrollY(); 1713 final boolean canFling = (scrollY > 0 || velocityY > 0) 1714 && (scrollY < getScrollRange() || velocityY < 0); 1715 if (!dispatchNestedPreFling(0, velocityY)) { 1716 dispatchNestedFling(0, velocityY, canFling); 1717 if (canFling) { 1718 fling(velocityY); 1719 } 1720 } 1721 } 1722 1723 private void endDrag() { 1724 mIsBeingDragged = false; 1725 1726 recycleVelocityTracker(); 1727 stopNestedScroll(); 1728 1729 if (mEdgeGlowTop != null) { 1730 mEdgeGlowTop.onRelease(); 1731 mEdgeGlowBottom.onRelease(); 1732 } 1733 } 1734 1735 /** 1736 * {@inheritDoc} 1737 * 1738 * <p>This version also clamps the scrolling to the bounds of our child. 1739 */ 1740 @Override 1741 public void scrollTo(int x, int y) { 1742 // we rely on the fact the View.scrollBy calls scrollTo. 1743 if (getChildCount() > 0) { 1744 View child = getChildAt(0); 1745 x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth()); 1746 y = clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight()); 1747 if (x != getScrollX() || y != getScrollY()) { 1748 super.scrollTo(x, y); 1749 } 1750 } 1751 } 1752 1753 private void ensureGlows() { 1754 if (getOverScrollMode() != View.OVER_SCROLL_NEVER) { 1755 if (mEdgeGlowTop == null) { 1756 Context context = getContext(); 1757 mEdgeGlowTop = new EdgeEffectCompat(context); 1758 mEdgeGlowBottom = new EdgeEffectCompat(context); 1759 } 1760 } else { 1761 mEdgeGlowTop = null; 1762 mEdgeGlowBottom = null; 1763 } 1764 } 1765 1766 @Override 1767 public void draw(Canvas canvas) { 1768 super.draw(canvas); 1769 if (mEdgeGlowTop != null) { 1770 final int scrollY = getScrollY(); 1771 if (!mEdgeGlowTop.isFinished()) { 1772 final int restoreCount = canvas.save(); 1773 final int width = getWidth() - getPaddingLeft() - getPaddingRight(); 1774 1775 canvas.translate(getPaddingLeft(), Math.min(0, scrollY)); 1776 mEdgeGlowTop.setSize(width, getHeight()); 1777 if (mEdgeGlowTop.draw(canvas)) { 1778 ViewCompat.postInvalidateOnAnimation(this); 1779 } 1780 canvas.restoreToCount(restoreCount); 1781 } 1782 if (!mEdgeGlowBottom.isFinished()) { 1783 final int restoreCount = canvas.save(); 1784 final int width = getWidth() - getPaddingLeft() - getPaddingRight(); 1785 final int height = getHeight(); 1786 1787 canvas.translate(-width + getPaddingLeft(), 1788 Math.max(getScrollRange(), scrollY) + height); 1789 canvas.rotate(180, width, 0); 1790 mEdgeGlowBottom.setSize(width, height); 1791 if (mEdgeGlowBottom.draw(canvas)) { 1792 ViewCompat.postInvalidateOnAnimation(this); 1793 } 1794 canvas.restoreToCount(restoreCount); 1795 } 1796 } 1797 } 1798 1799 private static int clamp(int n, int my, int child) { 1800 if (my >= child || n < 0) { 1801 /* my >= child is this case: 1802 * |--------------- me ---------------| 1803 * |------ child ------| 1804 * or 1805 * |--------------- me ---------------| 1806 * |------ child ------| 1807 * or 1808 * |--------------- me ---------------| 1809 * |------ child ------| 1810 * 1811 * n < 0 is this case: 1812 * |------ me ------| 1813 * |-------- child --------| 1814 * |-- mScrollX --| 1815 */ 1816 return 0; 1817 } 1818 if ((my + n) > child) { 1819 /* this case: 1820 * |------ me ------| 1821 * |------ child ------| 1822 * |-- mScrollX --| 1823 */ 1824 return child - my; 1825 } 1826 return n; 1827 } 1828 1829 @Override 1830 protected void onRestoreInstanceState(Parcelable state) { 1831 if (!(state instanceof SavedState)) { 1832 super.onRestoreInstanceState(state); 1833 return; 1834 } 1835 1836 SavedState ss = (SavedState) state; 1837 super.onRestoreInstanceState(ss.getSuperState()); 1838 mSavedState = ss; 1839 requestLayout(); 1840 } 1841 1842 @Override 1843 protected Parcelable onSaveInstanceState() { 1844 Parcelable superState = super.onSaveInstanceState(); 1845 SavedState ss = new SavedState(superState); 1846 ss.scrollPosition = getScrollY(); 1847 return ss; 1848 } 1849 1850 static class SavedState extends BaseSavedState { 1851 public int scrollPosition; 1852 1853 SavedState(Parcelable superState) { 1854 super(superState); 1855 } 1856 1857 SavedState(Parcel source) { 1858 super(source); 1859 scrollPosition = source.readInt(); 1860 } 1861 1862 @Override 1863 public void writeToParcel(Parcel dest, int flags) { 1864 super.writeToParcel(dest, flags); 1865 dest.writeInt(scrollPosition); 1866 } 1867 1868 @Override 1869 public String toString() { 1870 return "HorizontalScrollView.SavedState{" 1871 + Integer.toHexString(System.identityHashCode(this)) 1872 + " scrollPosition=" + scrollPosition + "}"; 1873 } 1874 1875 public static final Parcelable.Creator<SavedState> CREATOR = 1876 new Parcelable.Creator<SavedState>() { 1877 @Override 1878 public SavedState createFromParcel(Parcel in) { 1879 return new SavedState(in); 1880 } 1881 1882 @Override 1883 public SavedState[] newArray(int size) { 1884 return new SavedState[size]; 1885 } 1886 }; 1887 } 1888 1889 static class AccessibilityDelegate extends AccessibilityDelegateCompat { 1890 @Override 1891 public boolean performAccessibilityAction(View host, int action, Bundle arguments) { 1892 if (super.performAccessibilityAction(host, action, arguments)) { 1893 return true; 1894 } 1895 final NestedScrollView nsvHost = (NestedScrollView) host; 1896 if (!nsvHost.isEnabled()) { 1897 return false; 1898 } 1899 switch (action) { 1900 case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: { 1901 final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() 1902 - nsvHost.getPaddingTop(); 1903 final int targetScrollY = Math.min(nsvHost.getScrollY() + viewportHeight, 1904 nsvHost.getScrollRange()); 1905 if (targetScrollY != nsvHost.getScrollY()) { 1906 nsvHost.smoothScrollTo(0, targetScrollY); 1907 return true; 1908 } 1909 } 1910 return false; 1911 case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: { 1912 final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() 1913 - nsvHost.getPaddingTop(); 1914 final int targetScrollY = Math.max(nsvHost.getScrollY() - viewportHeight, 0); 1915 if (targetScrollY != nsvHost.getScrollY()) { 1916 nsvHost.smoothScrollTo(0, targetScrollY); 1917 return true; 1918 } 1919 } 1920 return false; 1921 } 1922 return false; 1923 } 1924 1925 @Override 1926 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { 1927 super.onInitializeAccessibilityNodeInfo(host, info); 1928 final NestedScrollView nsvHost = (NestedScrollView) host; 1929 info.setClassName(ScrollView.class.getName()); 1930 if (nsvHost.isEnabled()) { 1931 final int scrollRange = nsvHost.getScrollRange(); 1932 if (scrollRange > 0) { 1933 info.setScrollable(true); 1934 if (nsvHost.getScrollY() > 0) { 1935 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); 1936 } 1937 if (nsvHost.getScrollY() < scrollRange) { 1938 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); 1939 } 1940 } 1941 } 1942 } 1943 1944 @Override 1945 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 1946 super.onInitializeAccessibilityEvent(host, event); 1947 final NestedScrollView nsvHost = (NestedScrollView) host; 1948 event.setClassName(ScrollView.class.getName()); 1949 final AccessibilityRecordCompat record = AccessibilityEventCompat.asRecord(event); 1950 final boolean scrollable = nsvHost.getScrollRange() > 0; 1951 record.setScrollable(scrollable); 1952 record.setScrollX(nsvHost.getScrollX()); 1953 record.setScrollY(nsvHost.getScrollY()); 1954 record.setMaxScrollX(nsvHost.getScrollX()); 1955 record.setMaxScrollY(nsvHost.getScrollRange()); 1956 } 1957 } 1958} 1959