NestedScrollView.java revision 4d2c7b7c4f194034c5f17c4bee7320d808aabe4c
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.v4.view.AccessibilityDelegateCompat; 28import android.support.v4.view.InputDeviceCompat; 29import android.support.v4.view.MotionEventCompat; 30import android.support.v4.view.NestedScrollingChild; 31import android.support.v4.view.NestedScrollingChildHelper; 32import android.support.v4.view.NestedScrollingParent; 33import android.support.v4.view.NestedScrollingParentHelper; 34import android.support.v4.view.ScrollingView; 35import android.support.v4.view.VelocityTrackerCompat; 36import android.support.v4.view.ViewCompat; 37import android.support.v4.view.accessibility.AccessibilityEventCompat; 38import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; 39import android.support.v4.view.accessibility.AccessibilityRecordCompat; 40import android.util.AttributeSet; 41import android.util.Log; 42import android.util.TypedValue; 43import android.view.FocusFinder; 44import android.view.KeyEvent; 45import android.view.MotionEvent; 46import android.view.VelocityTracker; 47import android.view.View; 48import android.view.ViewConfiguration; 49import android.view.ViewGroup; 50import android.view.ViewParent; 51import android.view.accessibility.AccessibilityEvent; 52import android.view.animation.AnimationUtils; 53import android.widget.FrameLayout; 54import android.widget.ScrollView; 55 56import java.util.List; 57 58/** 59 * NestedScrollView is just like {@link android.widget.ScrollView}, but it supports acting 60 * as both a nested scrolling parent and child on both new and old versions of Android. 61 * Nested scrolling is enabled by default. 62 */ 63public class NestedScrollView extends FrameLayout implements NestedScrollingParent, 64 NestedScrollingChild, ScrollingView { 65 static final int ANIMATED_SCROLL_GAP = 250; 66 67 static final float MAX_SCROLL_FACTOR = 0.5f; 68 69 private static final String TAG = "NestedScrollView"; 70 71 /** 72 * Interface definition for a callback to be invoked when the scroll 73 * X or Y positions of a view change. 74 * 75 * <p>This version of the interface works on all versions of Android, back to API v4.</p> 76 * 77 * @see #setOnScrollChangeListener(OnScrollChangeListener) 78 */ 79 public interface OnScrollChangeListener { 80 /** 81 * Called when the scroll position of a view changes. 82 * 83 * @param v The view whose scroll position has changed. 84 * @param scrollX Current horizontal scroll origin. 85 * @param scrollY Current vertical scroll origin. 86 * @param oldScrollX Previous horizontal scroll origin. 87 * @param oldScrollY Previous vertical scroll origin. 88 */ 89 void onScrollChange(NestedScrollView v, int scrollX, int scrollY, 90 int oldScrollX, int oldScrollY); 91 } 92 93 private long mLastScroll; 94 95 private final Rect mTempRect = new Rect(); 96 private ScrollerCompat mScroller; 97 private EdgeEffectCompat mEdgeGlowTop; 98 private EdgeEffectCompat mEdgeGlowBottom; 99 100 /** 101 * Position of the last motion event. 102 */ 103 private int mLastMotionY; 104 105 /** 106 * True when the layout has changed but the traversal has not come through yet. 107 * Ideally the view hierarchy would keep track of this for us. 108 */ 109 private boolean mIsLayoutDirty = true; 110 private boolean mIsLaidOut = false; 111 112 /** 113 * The child to give focus to in the event that a child has requested focus while the 114 * layout is dirty. This prevents the scroll from being wrong if the child has not been 115 * laid out before requesting focus. 116 */ 117 private View mChildToScrollTo = null; 118 119 /** 120 * True if the user is currently dragging this ScrollView around. This is 121 * not the same as 'is being flinged', which can be checked by 122 * mScroller.isFinished() (flinging begins when the user lifts his finger). 123 */ 124 private boolean mIsBeingDragged = false; 125 126 /** 127 * Determines speed during touch scrolling 128 */ 129 private VelocityTracker mVelocityTracker; 130 131 /** 132 * When set to true, the scroll view measure its child to make it fill the currently 133 * visible area. 134 */ 135 private boolean mFillViewport; 136 137 /** 138 * Whether arrow scrolling is animated. 139 */ 140 private boolean mSmoothScrollingEnabled = true; 141 142 private int mTouchSlop; 143 private int mMinimumVelocity; 144 private int mMaximumVelocity; 145 146 /** 147 * ID of the active pointer. This is used to retain consistency during 148 * drags/flings if multiple pointers are used. 149 */ 150 private int mActivePointerId = INVALID_POINTER; 151 152 /** 153 * Used during scrolling to retrieve the new offset within the window. 154 */ 155 private final int[] mScrollOffset = new int[2]; 156 private final int[] mScrollConsumed = new int[2]; 157 private int mNestedYOffset; 158 159 /** 160 * Sentinel value for no current active pointer. 161 * Used by {@link #mActivePointerId}. 162 */ 163 private static final int INVALID_POINTER = -1; 164 165 private SavedState mSavedState; 166 167 private static final AccessibilityDelegate ACCESSIBILITY_DELEGATE = new AccessibilityDelegate(); 168 169 private static final int[] SCROLLVIEW_STYLEABLE = new int[] { 170 android.R.attr.fillViewport 171 }; 172 173 private final NestedScrollingParentHelper mParentHelper; 174 private final NestedScrollingChildHelper mChildHelper; 175 176 private float mVerticalScrollFactor; 177 178 private OnScrollChangeListener mOnScrollChangeListener; 179 180 public NestedScrollView(Context context) { 181 this(context, null); 182 } 183 184 public NestedScrollView(Context context, AttributeSet attrs) { 185 this(context, attrs, 0); 186 } 187 188 public NestedScrollView(Context context, AttributeSet attrs, int defStyleAttr) { 189 super(context, attrs, defStyleAttr); 190 initScrollView(); 191 192 final TypedArray a = context.obtainStyledAttributes( 193 attrs, SCROLLVIEW_STYLEABLE, defStyleAttr, 0); 194 195 setFillViewport(a.getBoolean(0, false)); 196 197 a.recycle(); 198 199 mParentHelper = new NestedScrollingParentHelper(this); 200 mChildHelper = new NestedScrollingChildHelper(this); 201 202 // ...because why else would you be using this widget? 203 setNestedScrollingEnabled(true); 204 205 ViewCompat.setAccessibilityDelegate(this, ACCESSIBILITY_DELEGATE); 206 } 207 208 // NestedScrollingChild 209 210 @Override 211 public void setNestedScrollingEnabled(boolean enabled) { 212 mChildHelper.setNestedScrollingEnabled(enabled); 213 } 214 215 @Override 216 public boolean isNestedScrollingEnabled() { 217 return mChildHelper.isNestedScrollingEnabled(); 218 } 219 220 @Override 221 public boolean startNestedScroll(int axes) { 222 return mChildHelper.startNestedScroll(axes); 223 } 224 225 @Override 226 public void stopNestedScroll() { 227 mChildHelper.stopNestedScroll(); 228 } 229 230 @Override 231 public boolean hasNestedScrollingParent() { 232 return mChildHelper.hasNestedScrollingParent(); 233 } 234 235 @Override 236 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, 237 int dyUnconsumed, int[] offsetInWindow) { 238 return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, 239 offsetInWindow); 240 } 241 242 @Override 243 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 244 return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow); 245 } 246 247 @Override 248 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 249 return mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed); 250 } 251 252 @Override 253 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 254 return mChildHelper.dispatchNestedPreFling(velocityX, velocityY); 255 } 256 257 // NestedScrollingParent 258 259 @Override 260 public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { 261 return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0; 262 } 263 264 @Override 265 public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) { 266 mParentHelper.onNestedScrollAccepted(child, target, nestedScrollAxes); 267 startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL); 268 } 269 270 @Override 271 public void onStopNestedScroll(View target) { 272 mParentHelper.onStopNestedScroll(target); 273 stopNestedScroll(); 274 } 275 276 @Override 277 public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, 278 int dyUnconsumed) { 279 final int oldScrollY = getScrollY(); 280 scrollBy(0, dyUnconsumed); 281 final int myConsumed = getScrollY() - oldScrollY; 282 final int myUnconsumed = dyUnconsumed - myConsumed; 283 dispatchNestedScroll(0, myConsumed, 0, myUnconsumed, null); 284 } 285 286 @Override 287 public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { 288 dispatchNestedPreScroll(dx, dy, consumed, null); 289 } 290 291 @Override 292 public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { 293 if (!consumed) { 294 flingWithNestedDispatch((int) velocityY); 295 return true; 296 } 297 return false; 298 } 299 300 @Override 301 public boolean onNestedPreFling(View target, float velocityX, float velocityY) { 302 return dispatchNestedPreFling(velocityX, velocityY); 303 } 304 305 @Override 306 public int getNestedScrollAxes() { 307 return mParentHelper.getNestedScrollAxes(); 308 } 309 310 // ScrollView import 311 312 public boolean shouldDelayChildPressedState() { 313 return true; 314 } 315 316 @Override 317 protected float getTopFadingEdgeStrength() { 318 if (getChildCount() == 0) { 319 return 0.0f; 320 } 321 322 final int length = getVerticalFadingEdgeLength(); 323 final int scrollY = getScrollY(); 324 if (scrollY < length) { 325 return scrollY / (float) length; 326 } 327 328 return 1.0f; 329 } 330 331 @Override 332 protected float getBottomFadingEdgeStrength() { 333 if (getChildCount() == 0) { 334 return 0.0f; 335 } 336 337 final int length = getVerticalFadingEdgeLength(); 338 final int bottomEdge = getHeight() - getPaddingBottom(); 339 final int span = getChildAt(0).getBottom() - getScrollY() - bottomEdge; 340 if (span < length) { 341 return span / (float) length; 342 } 343 344 return 1.0f; 345 } 346 347 /** 348 * @return The maximum amount this scroll view will scroll in response to 349 * an arrow event. 350 */ 351 public int getMaxScrollAmount() { 352 return (int) (MAX_SCROLL_FACTOR * getHeight()); 353 } 354 355 private void initScrollView() { 356 mScroller = ScrollerCompat.create(getContext(), null); 357 setFocusable(true); 358 setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); 359 setWillNotDraw(false); 360 final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 361 mTouchSlop = configuration.getScaledTouchSlop(); 362 mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); 363 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 364 } 365 366 @Override 367 public void addView(View child) { 368 if (getChildCount() > 0) { 369 throw new IllegalStateException("ScrollView can host only one direct child"); 370 } 371 372 super.addView(child); 373 } 374 375 @Override 376 public void addView(View child, int index) { 377 if (getChildCount() > 0) { 378 throw new IllegalStateException("ScrollView can host only one direct child"); 379 } 380 381 super.addView(child, index); 382 } 383 384 @Override 385 public void addView(View child, ViewGroup.LayoutParams params) { 386 if (getChildCount() > 0) { 387 throw new IllegalStateException("ScrollView can host only one direct child"); 388 } 389 390 super.addView(child, params); 391 } 392 393 @Override 394 public void addView(View child, int index, ViewGroup.LayoutParams params) { 395 if (getChildCount() > 0) { 396 throw new IllegalStateException("ScrollView can host only one direct child"); 397 } 398 399 super.addView(child, index, params); 400 } 401 402 /** 403 * Register a callback to be invoked when the scroll X or Y positions of 404 * this view change. 405 * <p>This version of the method works on all versions of Android, back to API v4.</p> 406 * 407 * @param l The listener to notify when the scroll X or Y position changes. 408 * @see android.view.View#getScrollX() 409 * @see android.view.View#getScrollY() 410 */ 411 public void setOnScrollChangeListener(OnScrollChangeListener l) { 412 mOnScrollChangeListener = l; 413 } 414 415 /** 416 * @return Returns true this ScrollView can be scrolled 417 */ 418 private boolean canScroll() { 419 View child = getChildAt(0); 420 if (child != null) { 421 int childHeight = child.getHeight(); 422 return getHeight() < childHeight + getPaddingTop() + getPaddingBottom(); 423 } 424 return false; 425 } 426 427 /** 428 * Indicates whether this ScrollView's content is stretched to fill the viewport. 429 * 430 * @return True if the content fills the viewport, false otherwise. 431 * 432 * @attr name android:fillViewport 433 */ 434 public boolean isFillViewport() { 435 return mFillViewport; 436 } 437 438 /** 439 * Set whether this ScrollView should stretch its content height to fill the viewport or not. 440 * 441 * @param fillViewport True to stretch the content's height to the viewport's 442 * boundaries, false otherwise. 443 * 444 * @attr name android:fillViewport 445 */ 446 public void setFillViewport(boolean fillViewport) { 447 if (fillViewport != mFillViewport) { 448 mFillViewport = fillViewport; 449 requestLayout(); 450 } 451 } 452 453 /** 454 * @return Whether arrow scrolling will animate its transition. 455 */ 456 public boolean isSmoothScrollingEnabled() { 457 return mSmoothScrollingEnabled; 458 } 459 460 /** 461 * Set whether arrow scrolling will animate its transition. 462 * @param smoothScrollingEnabled whether arrow scrolling will animate its transition 463 */ 464 public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) { 465 mSmoothScrollingEnabled = smoothScrollingEnabled; 466 } 467 468 @Override 469 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 470 super.onScrollChanged(l, t, oldl, oldt); 471 472 if (mOnScrollChangeListener != null) { 473 mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 474 } 475 } 476 477 @Override 478 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 479 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 480 481 if (!mFillViewport) { 482 return; 483 } 484 485 final int heightMode = MeasureSpec.getMode(heightMeasureSpec); 486 if (heightMode == MeasureSpec.UNSPECIFIED) { 487 return; 488 } 489 490 if (getChildCount() > 0) { 491 final View child = getChildAt(0); 492 int height = getMeasuredHeight(); 493 if (child.getMeasuredHeight() < height) { 494 final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); 495 496 int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 497 getPaddingLeft() + getPaddingRight(), lp.width); 498 height -= getPaddingTop(); 499 height -= getPaddingBottom(); 500 int childHeightMeasureSpec = 501 MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 502 503 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 504 } 505 } 506 } 507 508 @Override 509 public boolean dispatchKeyEvent(KeyEvent event) { 510 // Let the focused view and/or our descendants get the key first 511 return super.dispatchKeyEvent(event) || executeKeyEvent(event); 512 } 513 514 /** 515 * You can call this function yourself to have the scroll view perform 516 * scrolling from a key event, just as if the event had been dispatched to 517 * it by the view hierarchy. 518 * 519 * @param event The key event to execute. 520 * @return Return true if the event was handled, else false. 521 */ 522 public boolean executeKeyEvent(KeyEvent event) { 523 mTempRect.setEmpty(); 524 525 if (!canScroll()) { 526 if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) { 527 View currentFocused = findFocus(); 528 if (currentFocused == this) currentFocused = null; 529 View nextFocused = FocusFinder.getInstance().findNextFocus(this, 530 currentFocused, View.FOCUS_DOWN); 531 return nextFocused != null 532 && nextFocused != this 533 && nextFocused.requestFocus(View.FOCUS_DOWN); 534 } 535 return false; 536 } 537 538 boolean handled = false; 539 if (event.getAction() == KeyEvent.ACTION_DOWN) { 540 switch (event.getKeyCode()) { 541 case KeyEvent.KEYCODE_DPAD_UP: 542 if (!event.isAltPressed()) { 543 handled = arrowScroll(View.FOCUS_UP); 544 } else { 545 handled = fullScroll(View.FOCUS_UP); 546 } 547 break; 548 case KeyEvent.KEYCODE_DPAD_DOWN: 549 if (!event.isAltPressed()) { 550 handled = arrowScroll(View.FOCUS_DOWN); 551 } else { 552 handled = fullScroll(View.FOCUS_DOWN); 553 } 554 break; 555 case KeyEvent.KEYCODE_SPACE: 556 pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN); 557 break; 558 } 559 } 560 561 return handled; 562 } 563 564 private boolean inChild(int x, int y) { 565 if (getChildCount() > 0) { 566 final int scrollY = getScrollY(); 567 final View child = getChildAt(0); 568 return !(y < child.getTop() - scrollY 569 || y >= child.getBottom() - scrollY 570 || x < child.getLeft() 571 || x >= child.getRight()); 572 } 573 return false; 574 } 575 576 private void initOrResetVelocityTracker() { 577 if (mVelocityTracker == null) { 578 mVelocityTracker = VelocityTracker.obtain(); 579 } else { 580 mVelocityTracker.clear(); 581 } 582 } 583 584 private void initVelocityTrackerIfNotExists() { 585 if (mVelocityTracker == null) { 586 mVelocityTracker = VelocityTracker.obtain(); 587 } 588 } 589 590 private void recycleVelocityTracker() { 591 if (mVelocityTracker != null) { 592 mVelocityTracker.recycle(); 593 mVelocityTracker = null; 594 } 595 } 596 597 @Override 598 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 599 if (disallowIntercept) { 600 recycleVelocityTracker(); 601 } 602 super.requestDisallowInterceptTouchEvent(disallowIntercept); 603 } 604 605 606 @Override 607 public boolean onInterceptTouchEvent(MotionEvent ev) { 608 /* 609 * This method JUST determines whether we want to intercept the motion. 610 * If we return true, onMotionEvent will be called and we do the actual 611 * scrolling there. 612 */ 613 614 /* 615 * Shortcut the most recurring case: the user is in the dragging 616 * state and he is moving his finger. We want to intercept this 617 * motion. 618 */ 619 final int action = ev.getAction(); 620 if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { 621 return true; 622 } 623 624 switch (action & MotionEventCompat.ACTION_MASK) { 625 case MotionEvent.ACTION_MOVE: { 626 /* 627 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 628 * whether the user has moved far enough from his original down touch. 629 */ 630 631 /* 632 * Locally do absolute value. mLastMotionY is set to the y value 633 * of the down event. 634 */ 635 final int activePointerId = mActivePointerId; 636 if (activePointerId == INVALID_POINTER) { 637 // If we don't have a valid id, the touch down wasn't on content. 638 break; 639 } 640 641 final int pointerIndex = ev.findPointerIndex(activePointerId); 642 if (pointerIndex == -1) { 643 Log.e(TAG, "Invalid pointerId=" + activePointerId 644 + " in onInterceptTouchEvent"); 645 break; 646 } 647 648 final int y = (int) ev.getY(pointerIndex); 649 final int yDiff = Math.abs(y - mLastMotionY); 650 if (yDiff > mTouchSlop 651 && (getNestedScrollAxes() & ViewCompat.SCROLL_AXIS_VERTICAL) == 0) { 652 mIsBeingDragged = true; 653 mLastMotionY = y; 654 initVelocityTrackerIfNotExists(); 655 mVelocityTracker.addMovement(ev); 656 mNestedYOffset = 0; 657 final ViewParent parent = getParent(); 658 if (parent != null) { 659 parent.requestDisallowInterceptTouchEvent(true); 660 } 661 } 662 break; 663 } 664 665 case MotionEvent.ACTION_DOWN: { 666 final int y = (int) ev.getY(); 667 if (!inChild((int) ev.getX(), (int) y)) { 668 mIsBeingDragged = false; 669 recycleVelocityTracker(); 670 break; 671 } 672 673 /* 674 * Remember location of down touch. 675 * ACTION_DOWN always refers to pointer index 0. 676 */ 677 mLastMotionY = y; 678 mActivePointerId = ev.getPointerId(0); 679 680 initOrResetVelocityTracker(); 681 mVelocityTracker.addMovement(ev); 682 /* 683 * If being flinged and user touches the screen, initiate drag; 684 * otherwise don't. mScroller.isFinished should be false when 685 * being flinged. We need to call computeScrollOffset() first so that 686 * isFinished() is correct. 687 */ 688 mScroller.computeScrollOffset(); 689 mIsBeingDragged = !mScroller.isFinished(); 690 startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL); 691 break; 692 } 693 694 case MotionEvent.ACTION_CANCEL: 695 case MotionEvent.ACTION_UP: 696 /* Release the drag */ 697 mIsBeingDragged = false; 698 mActivePointerId = INVALID_POINTER; 699 recycleVelocityTracker(); 700 if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) { 701 ViewCompat.postInvalidateOnAnimation(this); 702 } 703 stopNestedScroll(); 704 break; 705 case MotionEventCompat.ACTION_POINTER_UP: 706 onSecondaryPointerUp(ev); 707 break; 708 } 709 710 /* 711 * The only time we want to intercept motion events is if we are in the 712 * drag mode. 713 */ 714 return mIsBeingDragged; 715 } 716 717 @Override 718 public boolean onTouchEvent(MotionEvent ev) { 719 initVelocityTrackerIfNotExists(); 720 721 MotionEvent vtev = MotionEvent.obtain(ev); 722 723 final int actionMasked = MotionEventCompat.getActionMasked(ev); 724 725 if (actionMasked == MotionEvent.ACTION_DOWN) { 726 mNestedYOffset = 0; 727 } 728 vtev.offsetLocation(0, mNestedYOffset); 729 730 switch (actionMasked) { 731 case MotionEvent.ACTION_DOWN: { 732 if (getChildCount() == 0) { 733 return false; 734 } 735 if ((mIsBeingDragged = !mScroller.isFinished())) { 736 final ViewParent parent = getParent(); 737 if (parent != null) { 738 parent.requestDisallowInterceptTouchEvent(true); 739 } 740 } 741 742 /* 743 * If being flinged and user touches, stop the fling. isFinished 744 * will be false if being flinged. 745 */ 746 if (!mScroller.isFinished()) { 747 mScroller.abortAnimation(); 748 } 749 750 // Remember where the motion event started 751 mLastMotionY = (int) ev.getY(); 752 mActivePointerId = ev.getPointerId(0); 753 startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL); 754 break; 755 } 756 case MotionEvent.ACTION_MOVE: 757 final int activePointerIndex = ev.findPointerIndex(mActivePointerId); 758 if (activePointerIndex == -1) { 759 Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent"); 760 break; 761 } 762 763 final int y = (int) ev.getY(activePointerIndex); 764 int deltaY = mLastMotionY - y; 765 if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) { 766 deltaY -= mScrollConsumed[1]; 767 vtev.offsetLocation(0, mScrollOffset[1]); 768 mNestedYOffset += mScrollOffset[1]; 769 } 770 if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) { 771 final ViewParent parent = getParent(); 772 if (parent != null) { 773 parent.requestDisallowInterceptTouchEvent(true); 774 } 775 mIsBeingDragged = true; 776 if (deltaY > 0) { 777 deltaY -= mTouchSlop; 778 } else { 779 deltaY += mTouchSlop; 780 } 781 } 782 if (mIsBeingDragged) { 783 // Scroll to follow the motion event 784 mLastMotionY = y - mScrollOffset[1]; 785 786 final int oldY = getScrollY(); 787 final int range = getScrollRange(); 788 final int overscrollMode = getOverScrollMode(); 789 boolean canOverscroll = overscrollMode == View.OVER_SCROLL_ALWAYS 790 || (overscrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); 791 792 // Calling overScrollByCompat will call onOverScrolled, which 793 // calls onScrollChanged if applicable. 794 if (overScrollByCompat(0, deltaY, 0, getScrollY(), 0, range, 0, 795 0, true) && !hasNestedScrollingParent()) { 796 // Break our velocity if we hit a scroll barrier. 797 mVelocityTracker.clear(); 798 } 799 800 final int scrolledDeltaY = getScrollY() - oldY; 801 final int unconsumedY = deltaY - scrolledDeltaY; 802 if (dispatchNestedScroll(0, scrolledDeltaY, 0, unconsumedY, mScrollOffset)) { 803 mLastMotionY -= mScrollOffset[1]; 804 vtev.offsetLocation(0, mScrollOffset[1]); 805 mNestedYOffset += mScrollOffset[1]; 806 } else if (canOverscroll) { 807 ensureGlows(); 808 final int pulledToY = oldY + deltaY; 809 if (pulledToY < 0) { 810 mEdgeGlowTop.onPull((float) deltaY / getHeight(), 811 ev.getX(activePointerIndex) / getWidth()); 812 if (!mEdgeGlowBottom.isFinished()) { 813 mEdgeGlowBottom.onRelease(); 814 } 815 } else if (pulledToY > range) { 816 mEdgeGlowBottom.onPull((float) deltaY / getHeight(), 817 1.f - ev.getX(activePointerIndex) 818 / getWidth()); 819 if (!mEdgeGlowTop.isFinished()) { 820 mEdgeGlowTop.onRelease(); 821 } 822 } 823 if (mEdgeGlowTop != null 824 && (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) { 825 ViewCompat.postInvalidateOnAnimation(this); 826 } 827 } 828 } 829 break; 830 case MotionEvent.ACTION_UP: 831 if (mIsBeingDragged) { 832 final VelocityTracker velocityTracker = mVelocityTracker; 833 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 834 int initialVelocity = (int) VelocityTrackerCompat.getYVelocity(velocityTracker, 835 mActivePointerId); 836 837 if ((Math.abs(initialVelocity) > mMinimumVelocity)) { 838 flingWithNestedDispatch(-initialVelocity); 839 } else if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, 840 getScrollRange())) { 841 ViewCompat.postInvalidateOnAnimation(this); 842 } 843 } 844 mActivePointerId = INVALID_POINTER; 845 endDrag(); 846 break; 847 case MotionEvent.ACTION_CANCEL: 848 if (mIsBeingDragged && getChildCount() > 0) { 849 if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, 850 getScrollRange())) { 851 ViewCompat.postInvalidateOnAnimation(this); 852 } 853 } 854 mActivePointerId = INVALID_POINTER; 855 endDrag(); 856 break; 857 case MotionEventCompat.ACTION_POINTER_DOWN: { 858 final int index = MotionEventCompat.getActionIndex(ev); 859 mLastMotionY = (int) ev.getY(index); 860 mActivePointerId = ev.getPointerId(index); 861 break; 862 } 863 case MotionEventCompat.ACTION_POINTER_UP: 864 onSecondaryPointerUp(ev); 865 mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId)); 866 break; 867 } 868 869 if (mVelocityTracker != null) { 870 mVelocityTracker.addMovement(vtev); 871 } 872 vtev.recycle(); 873 return true; 874 } 875 876 private void onSecondaryPointerUp(MotionEvent ev) { 877 final int pointerIndex = (ev.getAction() & MotionEventCompat.ACTION_POINTER_INDEX_MASK) 878 >> MotionEventCompat.ACTION_POINTER_INDEX_SHIFT; 879 final int pointerId = ev.getPointerId(pointerIndex); 880 if (pointerId == mActivePointerId) { 881 // This was our active pointer going up. Choose a new 882 // active pointer and adjust accordingly. 883 // TODO: Make this decision more intelligent. 884 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 885 mLastMotionY = (int) ev.getY(newPointerIndex); 886 mActivePointerId = ev.getPointerId(newPointerIndex); 887 if (mVelocityTracker != null) { 888 mVelocityTracker.clear(); 889 } 890 } 891 } 892 893 public boolean onGenericMotionEvent(MotionEvent event) { 894 if ((event.getSource() & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) { 895 switch (event.getAction()) { 896 case MotionEventCompat.ACTION_SCROLL: { 897 if (!mIsBeingDragged) { 898 final float vscroll = MotionEventCompat.getAxisValue(event, 899 MotionEventCompat.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 private 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 @Override 1335 public int computeVerticalScrollRange() { 1336 final int count = getChildCount(); 1337 final int contentHeight = getHeight() - getPaddingBottom() - getPaddingTop(); 1338 if (count == 0) { 1339 return contentHeight; 1340 } 1341 1342 int scrollRange = getChildAt(0).getBottom(); 1343 final int scrollY = getScrollY(); 1344 final int overscrollBottom = Math.max(0, scrollRange - contentHeight); 1345 if (scrollY < 0) { 1346 scrollRange -= scrollY; 1347 } else if (scrollY > overscrollBottom) { 1348 scrollRange += scrollY - overscrollBottom; 1349 } 1350 1351 return scrollRange; 1352 } 1353 1354 /** @hide */ 1355 @Override 1356 public int computeVerticalScrollOffset() { 1357 return Math.max(0, super.computeVerticalScrollOffset()); 1358 } 1359 1360 /** @hide */ 1361 @Override 1362 public int computeVerticalScrollExtent() { 1363 return super.computeVerticalScrollExtent(); 1364 } 1365 1366 /** @hide */ 1367 @Override 1368 public int computeHorizontalScrollRange() { 1369 return super.computeHorizontalScrollRange(); 1370 } 1371 1372 /** @hide */ 1373 @Override 1374 public int computeHorizontalScrollOffset() { 1375 return super.computeHorizontalScrollOffset(); 1376 } 1377 1378 /** @hide */ 1379 @Override 1380 public int computeHorizontalScrollExtent() { 1381 return super.computeHorizontalScrollExtent(); 1382 } 1383 1384 @Override 1385 protected void measureChild(View child, int parentWidthMeasureSpec, 1386 int parentHeightMeasureSpec) { 1387 ViewGroup.LayoutParams lp = child.getLayoutParams(); 1388 1389 int childWidthMeasureSpec; 1390 int childHeightMeasureSpec; 1391 1392 childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() 1393 + getPaddingRight(), lp.width); 1394 1395 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 1396 1397 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1398 } 1399 1400 @Override 1401 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 1402 int parentHeightMeasureSpec, int heightUsed) { 1403 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 1404 1405 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 1406 getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin 1407 + widthUsed, lp.width); 1408 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( 1409 lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED); 1410 1411 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1412 } 1413 1414 @Override 1415 public void computeScroll() { 1416 if (mScroller.computeScrollOffset()) { 1417 int oldX = getScrollX(); 1418 int oldY = getScrollY(); 1419 int x = mScroller.getCurrX(); 1420 int y = mScroller.getCurrY(); 1421 1422 if (oldX != x || oldY != y) { 1423 final int range = getScrollRange(); 1424 final int overscrollMode = getOverScrollMode(); 1425 final boolean canOverscroll = overscrollMode == View.OVER_SCROLL_ALWAYS 1426 || (overscrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); 1427 1428 overScrollByCompat(x - oldX, y - oldY, oldX, oldY, 0, range, 1429 0, 0, false); 1430 1431 if (canOverscroll) { 1432 ensureGlows(); 1433 if (y <= 0 && oldY > 0) { 1434 mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity()); 1435 } else if (y >= range && oldY < range) { 1436 mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity()); 1437 } 1438 } 1439 } 1440 } 1441 } 1442 1443 /** 1444 * Scrolls the view to the given child. 1445 * 1446 * @param child the View to scroll to 1447 */ 1448 private void scrollToChild(View child) { 1449 child.getDrawingRect(mTempRect); 1450 1451 /* Offset from child's local coordinates to ScrollView coordinates */ 1452 offsetDescendantRectToMyCoords(child, mTempRect); 1453 1454 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1455 1456 if (scrollDelta != 0) { 1457 scrollBy(0, scrollDelta); 1458 } 1459 } 1460 1461 /** 1462 * If rect is off screen, scroll just enough to get it (or at least the 1463 * first screen size chunk of it) on screen. 1464 * 1465 * @param rect The rectangle. 1466 * @param immediate True to scroll immediately without animation 1467 * @return true if scrolling was performed 1468 */ 1469 private boolean scrollToChildRect(Rect rect, boolean immediate) { 1470 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); 1471 final boolean scroll = delta != 0; 1472 if (scroll) { 1473 if (immediate) { 1474 scrollBy(0, delta); 1475 } else { 1476 smoothScrollBy(0, delta); 1477 } 1478 } 1479 return scroll; 1480 } 1481 1482 /** 1483 * Compute the amount to scroll in the Y direction in order to get 1484 * a rectangle completely on the screen (or, if taller than the screen, 1485 * at least the first screen size chunk of it). 1486 * 1487 * @param rect The rect. 1488 * @return The scroll delta. 1489 */ 1490 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { 1491 if (getChildCount() == 0) return 0; 1492 1493 int height = getHeight(); 1494 int screenTop = getScrollY(); 1495 int screenBottom = screenTop + height; 1496 1497 int fadingEdge = getVerticalFadingEdgeLength(); 1498 1499 // leave room for top fading edge as long as rect isn't at very top 1500 if (rect.top > 0) { 1501 screenTop += fadingEdge; 1502 } 1503 1504 // leave room for bottom fading edge as long as rect isn't at very bottom 1505 if (rect.bottom < getChildAt(0).getHeight()) { 1506 screenBottom -= fadingEdge; 1507 } 1508 1509 int scrollYDelta = 0; 1510 1511 if (rect.bottom > screenBottom && rect.top > screenTop) { 1512 // need to move down to get it in view: move down just enough so 1513 // that the entire rectangle is in view (or at least the first 1514 // screen size chunk). 1515 1516 if (rect.height() > height) { 1517 // just enough to get screen size chunk on 1518 scrollYDelta += (rect.top - screenTop); 1519 } else { 1520 // get entire rect at bottom of screen 1521 scrollYDelta += (rect.bottom - screenBottom); 1522 } 1523 1524 // make sure we aren't scrolling beyond the end of our content 1525 int bottom = getChildAt(0).getBottom(); 1526 int distanceToBottom = bottom - screenBottom; 1527 scrollYDelta = Math.min(scrollYDelta, distanceToBottom); 1528 1529 } else if (rect.top < screenTop && rect.bottom < screenBottom) { 1530 // need to move up to get it in view: move up just enough so that 1531 // entire rectangle is in view (or at least the first screen 1532 // size chunk of it). 1533 1534 if (rect.height() > height) { 1535 // screen size chunk 1536 scrollYDelta -= (screenBottom - rect.bottom); 1537 } else { 1538 // entire rect at top 1539 scrollYDelta -= (screenTop - rect.top); 1540 } 1541 1542 // make sure we aren't scrolling any further than the top our content 1543 scrollYDelta = Math.max(scrollYDelta, -getScrollY()); 1544 } 1545 return scrollYDelta; 1546 } 1547 1548 @Override 1549 public void requestChildFocus(View child, View focused) { 1550 if (!mIsLayoutDirty) { 1551 scrollToChild(focused); 1552 } else { 1553 // The child may not be laid out yet, we can't compute the scroll yet 1554 mChildToScrollTo = focused; 1555 } 1556 super.requestChildFocus(child, focused); 1557 } 1558 1559 1560 /** 1561 * When looking for focus in children of a scroll view, need to be a little 1562 * more careful not to give focus to something that is scrolled off screen. 1563 * 1564 * This is more expensive than the default {@link android.view.ViewGroup} 1565 * implementation, otherwise this behavior might have been made the default. 1566 */ 1567 @Override 1568 protected boolean onRequestFocusInDescendants(int direction, 1569 Rect previouslyFocusedRect) { 1570 1571 // convert from forward / backward notation to up / down / left / right 1572 // (ugh). 1573 if (direction == View.FOCUS_FORWARD) { 1574 direction = View.FOCUS_DOWN; 1575 } else if (direction == View.FOCUS_BACKWARD) { 1576 direction = View.FOCUS_UP; 1577 } 1578 1579 final View nextFocus = previouslyFocusedRect == null 1580 ? FocusFinder.getInstance().findNextFocus(this, null, direction) 1581 : FocusFinder.getInstance().findNextFocusFromRect( 1582 this, previouslyFocusedRect, direction); 1583 1584 if (nextFocus == null) { 1585 return false; 1586 } 1587 1588 if (isOffScreen(nextFocus)) { 1589 return false; 1590 } 1591 1592 return nextFocus.requestFocus(direction, previouslyFocusedRect); 1593 } 1594 1595 @Override 1596 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 1597 boolean immediate) { 1598 // offset into coordinate space of this scroll view 1599 rectangle.offset(child.getLeft() - child.getScrollX(), 1600 child.getTop() - child.getScrollY()); 1601 1602 return scrollToChildRect(rectangle, immediate); 1603 } 1604 1605 @Override 1606 public void requestLayout() { 1607 mIsLayoutDirty = true; 1608 super.requestLayout(); 1609 } 1610 1611 @Override 1612 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1613 super.onLayout(changed, l, t, r, b); 1614 mIsLayoutDirty = false; 1615 // Give a child focus if it needs it 1616 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { 1617 scrollToChild(mChildToScrollTo); 1618 } 1619 mChildToScrollTo = null; 1620 1621 if (!mIsLaidOut) { 1622 if (mSavedState != null) { 1623 scrollTo(getScrollX(), mSavedState.scrollPosition); 1624 mSavedState = null; 1625 } // mScrollY default value is "0" 1626 1627 final int childHeight = (getChildCount() > 0) ? getChildAt(0).getMeasuredHeight() : 0; 1628 final int scrollRange = Math.max(0, 1629 childHeight - (b - t - getPaddingBottom() - getPaddingTop())); 1630 1631 // Don't forget to clamp 1632 if (getScrollY() > scrollRange) { 1633 scrollTo(getScrollX(), scrollRange); 1634 } else if (getScrollY() < 0) { 1635 scrollTo(getScrollX(), 0); 1636 } 1637 } 1638 1639 // Calling this with the present values causes it to re-claim them 1640 scrollTo(getScrollX(), getScrollY()); 1641 mIsLaidOut = true; 1642 } 1643 1644 @Override 1645 public void onAttachedToWindow() { 1646 super.onAttachedToWindow(); 1647 1648 mIsLaidOut = false; 1649 } 1650 1651 @Override 1652 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1653 super.onSizeChanged(w, h, oldw, oldh); 1654 1655 View currentFocused = findFocus(); 1656 if (null == currentFocused || this == currentFocused) { 1657 return; 1658 } 1659 1660 // If the currently-focused view was visible on the screen when the 1661 // screen was at the old height, then scroll the screen to make that 1662 // view visible with the new screen height. 1663 if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) { 1664 currentFocused.getDrawingRect(mTempRect); 1665 offsetDescendantRectToMyCoords(currentFocused, mTempRect); 1666 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1667 doScrollY(scrollDelta); 1668 } 1669 } 1670 1671 /** 1672 * Return true if child is a descendant of parent, (or equal to the parent). 1673 */ 1674 private static boolean isViewDescendantOf(View child, View parent) { 1675 if (child == parent) { 1676 return true; 1677 } 1678 1679 final ViewParent theParent = child.getParent(); 1680 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 1681 } 1682 1683 /** 1684 * Fling the scroll view 1685 * 1686 * @param velocityY The initial velocity in the Y direction. Positive 1687 * numbers mean that the finger/cursor is moving down the screen, 1688 * which means we want to scroll towards the top. 1689 */ 1690 public void fling(int velocityY) { 1691 if (getChildCount() > 0) { 1692 int height = getHeight() - getPaddingBottom() - getPaddingTop(); 1693 int bottom = getChildAt(0).getHeight(); 1694 1695 mScroller.fling(getScrollX(), getScrollY(), 0, velocityY, 0, 0, 0, 1696 Math.max(0, bottom - height), 0, height / 2); 1697 1698 ViewCompat.postInvalidateOnAnimation(this); 1699 } 1700 } 1701 1702 private void flingWithNestedDispatch(int velocityY) { 1703 final int scrollY = getScrollY(); 1704 final boolean canFling = (scrollY > 0 || velocityY > 0) 1705 && (scrollY < getScrollRange() || velocityY < 0); 1706 if (!dispatchNestedPreFling(0, velocityY)) { 1707 dispatchNestedFling(0, velocityY, canFling); 1708 if (canFling) { 1709 fling(velocityY); 1710 } 1711 } 1712 } 1713 1714 private void endDrag() { 1715 mIsBeingDragged = false; 1716 1717 recycleVelocityTracker(); 1718 stopNestedScroll(); 1719 1720 if (mEdgeGlowTop != null) { 1721 mEdgeGlowTop.onRelease(); 1722 mEdgeGlowBottom.onRelease(); 1723 } 1724 } 1725 1726 /** 1727 * {@inheritDoc} 1728 * 1729 * <p>This version also clamps the scrolling to the bounds of our child. 1730 */ 1731 @Override 1732 public void scrollTo(int x, int y) { 1733 // we rely on the fact the View.scrollBy calls scrollTo. 1734 if (getChildCount() > 0) { 1735 View child = getChildAt(0); 1736 x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth()); 1737 y = clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight()); 1738 if (x != getScrollX() || y != getScrollY()) { 1739 super.scrollTo(x, y); 1740 } 1741 } 1742 } 1743 1744 private void ensureGlows() { 1745 if (getOverScrollMode() != View.OVER_SCROLL_NEVER) { 1746 if (mEdgeGlowTop == null) { 1747 Context context = getContext(); 1748 mEdgeGlowTop = new EdgeEffectCompat(context); 1749 mEdgeGlowBottom = new EdgeEffectCompat(context); 1750 } 1751 } else { 1752 mEdgeGlowTop = null; 1753 mEdgeGlowBottom = null; 1754 } 1755 } 1756 1757 @Override 1758 public void draw(Canvas canvas) { 1759 super.draw(canvas); 1760 if (mEdgeGlowTop != null) { 1761 final int scrollY = getScrollY(); 1762 if (!mEdgeGlowTop.isFinished()) { 1763 final int restoreCount = canvas.save(); 1764 final int width = getWidth() - getPaddingLeft() - getPaddingRight(); 1765 1766 canvas.translate(getPaddingLeft(), Math.min(0, scrollY)); 1767 mEdgeGlowTop.setSize(width, getHeight()); 1768 if (mEdgeGlowTop.draw(canvas)) { 1769 ViewCompat.postInvalidateOnAnimation(this); 1770 } 1771 canvas.restoreToCount(restoreCount); 1772 } 1773 if (!mEdgeGlowBottom.isFinished()) { 1774 final int restoreCount = canvas.save(); 1775 final int width = getWidth() - getPaddingLeft() - getPaddingRight(); 1776 final int height = getHeight(); 1777 1778 canvas.translate(-width + getPaddingLeft(), 1779 Math.max(getScrollRange(), scrollY) + height); 1780 canvas.rotate(180, width, 0); 1781 mEdgeGlowBottom.setSize(width, height); 1782 if (mEdgeGlowBottom.draw(canvas)) { 1783 ViewCompat.postInvalidateOnAnimation(this); 1784 } 1785 canvas.restoreToCount(restoreCount); 1786 } 1787 } 1788 } 1789 1790 private static int clamp(int n, int my, int child) { 1791 if (my >= child || n < 0) { 1792 /* my >= child is this case: 1793 * |--------------- me ---------------| 1794 * |------ child ------| 1795 * or 1796 * |--------------- me ---------------| 1797 * |------ child ------| 1798 * or 1799 * |--------------- me ---------------| 1800 * |------ child ------| 1801 * 1802 * n < 0 is this case: 1803 * |------ me ------| 1804 * |-------- child --------| 1805 * |-- mScrollX --| 1806 */ 1807 return 0; 1808 } 1809 if ((my + n) > child) { 1810 /* this case: 1811 * |------ me ------| 1812 * |------ child ------| 1813 * |-- mScrollX --| 1814 */ 1815 return child - my; 1816 } 1817 return n; 1818 } 1819 1820 @Override 1821 protected void onRestoreInstanceState(Parcelable state) { 1822 if (!(state instanceof SavedState)) { 1823 super.onRestoreInstanceState(state); 1824 return; 1825 } 1826 1827 SavedState ss = (SavedState) state; 1828 super.onRestoreInstanceState(ss.getSuperState()); 1829 mSavedState = ss; 1830 requestLayout(); 1831 } 1832 1833 @Override 1834 protected Parcelable onSaveInstanceState() { 1835 Parcelable superState = super.onSaveInstanceState(); 1836 SavedState ss = new SavedState(superState); 1837 ss.scrollPosition = getScrollY(); 1838 return ss; 1839 } 1840 1841 static class SavedState extends BaseSavedState { 1842 public int scrollPosition; 1843 1844 SavedState(Parcelable superState) { 1845 super(superState); 1846 } 1847 1848 SavedState(Parcel source) { 1849 super(source); 1850 scrollPosition = source.readInt(); 1851 } 1852 1853 @Override 1854 public void writeToParcel(Parcel dest, int flags) { 1855 super.writeToParcel(dest, flags); 1856 dest.writeInt(scrollPosition); 1857 } 1858 1859 @Override 1860 public String toString() { 1861 return "HorizontalScrollView.SavedState{" 1862 + Integer.toHexString(System.identityHashCode(this)) 1863 + " scrollPosition=" + scrollPosition + "}"; 1864 } 1865 1866 public static final Parcelable.Creator<SavedState> CREATOR = 1867 new Parcelable.Creator<SavedState>() { 1868 @Override 1869 public SavedState createFromParcel(Parcel in) { 1870 return new SavedState(in); 1871 } 1872 1873 @Override 1874 public SavedState[] newArray(int size) { 1875 return new SavedState[size]; 1876 } 1877 }; 1878 } 1879 1880 static class AccessibilityDelegate extends AccessibilityDelegateCompat { 1881 @Override 1882 public boolean performAccessibilityAction(View host, int action, Bundle arguments) { 1883 if (super.performAccessibilityAction(host, action, arguments)) { 1884 return true; 1885 } 1886 final NestedScrollView nsvHost = (NestedScrollView) host; 1887 if (!nsvHost.isEnabled()) { 1888 return false; 1889 } 1890 switch (action) { 1891 case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: { 1892 final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() 1893 - nsvHost.getPaddingTop(); 1894 final int targetScrollY = Math.min(nsvHost.getScrollY() + viewportHeight, 1895 nsvHost.getScrollRange()); 1896 if (targetScrollY != nsvHost.getScrollY()) { 1897 nsvHost.smoothScrollTo(0, targetScrollY); 1898 return true; 1899 } 1900 } 1901 return false; 1902 case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: { 1903 final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() 1904 - nsvHost.getPaddingTop(); 1905 final int targetScrollY = Math.max(nsvHost.getScrollY() - viewportHeight, 0); 1906 if (targetScrollY != nsvHost.getScrollY()) { 1907 nsvHost.smoothScrollTo(0, targetScrollY); 1908 return true; 1909 } 1910 } 1911 return false; 1912 } 1913 return false; 1914 } 1915 1916 @Override 1917 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { 1918 super.onInitializeAccessibilityNodeInfo(host, info); 1919 final NestedScrollView nsvHost = (NestedScrollView) host; 1920 info.setClassName(ScrollView.class.getName()); 1921 if (nsvHost.isEnabled()) { 1922 final int scrollRange = nsvHost.getScrollRange(); 1923 if (scrollRange > 0) { 1924 info.setScrollable(true); 1925 if (nsvHost.getScrollY() > 0) { 1926 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); 1927 } 1928 if (nsvHost.getScrollY() < scrollRange) { 1929 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); 1930 } 1931 } 1932 } 1933 } 1934 1935 @Override 1936 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 1937 super.onInitializeAccessibilityEvent(host, event); 1938 final NestedScrollView nsvHost = (NestedScrollView) host; 1939 event.setClassName(ScrollView.class.getName()); 1940 final AccessibilityRecordCompat record = AccessibilityEventCompat.asRecord(event); 1941 final boolean scrollable = nsvHost.getScrollRange() > 0; 1942 record.setScrollable(scrollable); 1943 record.setScrollX(nsvHost.getScrollX()); 1944 record.setScrollY(nsvHost.getScrollY()); 1945 record.setMaxScrollX(nsvHost.getScrollX()); 1946 record.setMaxScrollY(nsvHost.getScrollRange()); 1947 } 1948 } 1949} 1950