ScrollView.java revision e979e62ac7313b7cffe9b131bb8a99c356068b45
1/* 2 * Copyright (C) 2006 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 17package android.widget; 18 19import com.android.internal.R; 20 21import android.content.Context; 22import android.content.res.TypedArray; 23import android.graphics.Canvas; 24import android.graphics.Rect; 25import android.os.StrictMode; 26import android.util.AttributeSet; 27import android.view.FocusFinder; 28import android.view.InputDevice; 29import android.view.KeyEvent; 30import android.view.MotionEvent; 31import android.view.VelocityTracker; 32import android.view.View; 33import android.view.ViewConfiguration; 34import android.view.ViewDebug; 35import android.view.ViewGroup; 36import android.view.ViewParent; 37import android.view.accessibility.AccessibilityEvent; 38import android.view.accessibility.AccessibilityNodeInfo; 39import android.view.animation.AnimationUtils; 40 41import java.util.List; 42 43/** 44 * Layout container for a view hierarchy that can be scrolled by the user, 45 * allowing it to be larger than the physical display. A ScrollView 46 * is a {@link FrameLayout}, meaning you should place one child in it 47 * containing the entire contents to scroll; this child may itself be a layout 48 * manager with a complex hierarchy of objects. A child that is often used 49 * is a {@link LinearLayout} in a vertical orientation, presenting a vertical 50 * array of top-level items that the user can scroll through. 51 * 52 * <p>The {@link TextView} class also 53 * takes care of its own scrolling, so does not require a ScrollView, but 54 * using the two together is possible to achieve the effect of a text view 55 * within a larger container. 56 * 57 * <p>ScrollView only supports vertical scrolling. 58 * 59 * @attr ref android.R.styleable#ScrollView_fillViewport 60 */ 61public class ScrollView extends FrameLayout { 62 static final int ANIMATED_SCROLL_GAP = 250; 63 64 static final float MAX_SCROLL_FACTOR = 0.5f; 65 66 private long mLastScroll; 67 68 private final Rect mTempRect = new Rect(); 69 private OverScroller mScroller; 70 private EdgeEffect mEdgeGlowTop; 71 private EdgeEffect mEdgeGlowBottom; 72 73 /** 74 * Position of the last motion event. 75 */ 76 private float mLastMotionY; 77 78 /** 79 * True when the layout has changed but the traversal has not come through yet. 80 * Ideally the view hierarchy would keep track of this for us. 81 */ 82 private boolean mIsLayoutDirty = true; 83 84 /** 85 * The child to give focus to in the event that a child has requested focus while the 86 * layout is dirty. This prevents the scroll from being wrong if the child has not been 87 * laid out before requesting focus. 88 */ 89 private View mChildToScrollTo = null; 90 91 /** 92 * True if the user is currently dragging this ScrollView around. This is 93 * not the same as 'is being flinged', which can be checked by 94 * mScroller.isFinished() (flinging begins when the user lifts his finger). 95 */ 96 private boolean mIsBeingDragged = false; 97 98 /** 99 * Determines speed during touch scrolling 100 */ 101 private VelocityTracker mVelocityTracker; 102 103 /** 104 * When set to true, the scroll view measure its child to make it fill the currently 105 * visible area. 106 */ 107 @ViewDebug.ExportedProperty(category = "layout") 108 private boolean mFillViewport; 109 110 /** 111 * Whether arrow scrolling is animated. 112 */ 113 private boolean mSmoothScrollingEnabled = true; 114 115 private int mTouchSlop; 116 private int mMinimumVelocity; 117 private int mMaximumVelocity; 118 119 private int mOverscrollDistance; 120 private int mOverflingDistance; 121 122 /** 123 * ID of the active pointer. This is used to retain consistency during 124 * drags/flings if multiple pointers are used. 125 */ 126 private int mActivePointerId = INVALID_POINTER; 127 128 /** 129 * The StrictMode "critical time span" objects to catch animation 130 * stutters. Non-null when a time-sensitive animation is 131 * in-flight. Must call finish() on them when done animating. 132 * These are no-ops on user builds. 133 */ 134 private StrictMode.Span mScrollStrictSpan = null; // aka "drag" 135 private StrictMode.Span mFlingStrictSpan = null; 136 137 /** 138 * Sentinel value for no current active pointer. 139 * Used by {@link #mActivePointerId}. 140 */ 141 private static final int INVALID_POINTER = -1; 142 143 public ScrollView(Context context) { 144 this(context, null); 145 } 146 147 public ScrollView(Context context, AttributeSet attrs) { 148 this(context, attrs, com.android.internal.R.attr.scrollViewStyle); 149 } 150 151 public ScrollView(Context context, AttributeSet attrs, int defStyle) { 152 super(context, attrs, defStyle); 153 initScrollView(); 154 155 TypedArray a = 156 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ScrollView, defStyle, 0); 157 158 setFillViewport(a.getBoolean(R.styleable.ScrollView_fillViewport, false)); 159 160 a.recycle(); 161 } 162 163 @Override 164 public boolean shouldDelayChildPressedState() { 165 return true; 166 } 167 168 @Override 169 protected float getTopFadingEdgeStrength() { 170 if (getChildCount() == 0) { 171 return 0.0f; 172 } 173 174 final int length = getVerticalFadingEdgeLength(); 175 if (mScrollY < length) { 176 return mScrollY / (float) length; 177 } 178 179 return 1.0f; 180 } 181 182 @Override 183 protected float getBottomFadingEdgeStrength() { 184 if (getChildCount() == 0) { 185 return 0.0f; 186 } 187 188 final int length = getVerticalFadingEdgeLength(); 189 final int bottomEdge = getHeight() - mPaddingBottom; 190 final int span = getChildAt(0).getBottom() - mScrollY - bottomEdge; 191 if (span < length) { 192 return span / (float) length; 193 } 194 195 return 1.0f; 196 } 197 198 /** 199 * @return The maximum amount this scroll view will scroll in response to 200 * an arrow event. 201 */ 202 public int getMaxScrollAmount() { 203 return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop)); 204 } 205 206 207 private void initScrollView() { 208 mScroller = new OverScroller(getContext()); 209 setFocusable(true); 210 setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); 211 setWillNotDraw(false); 212 final ViewConfiguration configuration = ViewConfiguration.get(mContext); 213 mTouchSlop = configuration.getScaledTouchSlop(); 214 mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); 215 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 216 mOverscrollDistance = configuration.getScaledOverscrollDistance(); 217 mOverflingDistance = configuration.getScaledOverflingDistance(); 218 } 219 220 @Override 221 public void addView(View child) { 222 if (getChildCount() > 0) { 223 throw new IllegalStateException("ScrollView can host only one direct child"); 224 } 225 226 super.addView(child); 227 } 228 229 @Override 230 public void addView(View child, int index) { 231 if (getChildCount() > 0) { 232 throw new IllegalStateException("ScrollView can host only one direct child"); 233 } 234 235 super.addView(child, index); 236 } 237 238 @Override 239 public void addView(View child, ViewGroup.LayoutParams params) { 240 if (getChildCount() > 0) { 241 throw new IllegalStateException("ScrollView can host only one direct child"); 242 } 243 244 super.addView(child, params); 245 } 246 247 @Override 248 public void addView(View child, int index, ViewGroup.LayoutParams params) { 249 if (getChildCount() > 0) { 250 throw new IllegalStateException("ScrollView can host only one direct child"); 251 } 252 253 super.addView(child, index, params); 254 } 255 256 /** 257 * @return Returns true this ScrollView can be scrolled 258 */ 259 private boolean canScroll() { 260 View child = getChildAt(0); 261 if (child != null) { 262 int childHeight = child.getHeight(); 263 return getHeight() < childHeight + mPaddingTop + mPaddingBottom; 264 } 265 return false; 266 } 267 268 /** 269 * Indicates whether this ScrollView's content is stretched to fill the viewport. 270 * 271 * @return True if the content fills the viewport, false otherwise. 272 * 273 * @attr ref android.R.styleable#ScrollView_fillViewport 274 */ 275 public boolean isFillViewport() { 276 return mFillViewport; 277 } 278 279 /** 280 * Indicates this ScrollView whether it should stretch its content height to fill 281 * the viewport or not. 282 * 283 * @param fillViewport True to stretch the content's height to the viewport's 284 * boundaries, false otherwise. 285 * 286 * @attr ref android.R.styleable#ScrollView_fillViewport 287 */ 288 public void setFillViewport(boolean fillViewport) { 289 if (fillViewport != mFillViewport) { 290 mFillViewport = fillViewport; 291 requestLayout(); 292 } 293 } 294 295 /** 296 * @return Whether arrow scrolling will animate its transition. 297 */ 298 public boolean isSmoothScrollingEnabled() { 299 return mSmoothScrollingEnabled; 300 } 301 302 /** 303 * Set whether arrow scrolling will animate its transition. 304 * @param smoothScrollingEnabled whether arrow scrolling will animate its transition 305 */ 306 public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) { 307 mSmoothScrollingEnabled = smoothScrollingEnabled; 308 } 309 310 @Override 311 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 312 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 313 314 if (!mFillViewport) { 315 return; 316 } 317 318 final int heightMode = MeasureSpec.getMode(heightMeasureSpec); 319 if (heightMode == MeasureSpec.UNSPECIFIED) { 320 return; 321 } 322 323 if (getChildCount() > 0) { 324 final View child = getChildAt(0); 325 int height = getMeasuredHeight(); 326 if (child.getMeasuredHeight() < height) { 327 final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); 328 329 int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 330 mPaddingLeft + mPaddingRight, lp.width); 331 height -= mPaddingTop; 332 height -= mPaddingBottom; 333 int childHeightMeasureSpec = 334 MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 335 336 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 337 } 338 } 339 } 340 341 @Override 342 public boolean dispatchKeyEvent(KeyEvent event) { 343 // Let the focused view and/or our descendants get the key first 344 return super.dispatchKeyEvent(event) || executeKeyEvent(event); 345 } 346 347 /** 348 * You can call this function yourself to have the scroll view perform 349 * scrolling from a key event, just as if the event had been dispatched to 350 * it by the view hierarchy. 351 * 352 * @param event The key event to execute. 353 * @return Return true if the event was handled, else false. 354 */ 355 public boolean executeKeyEvent(KeyEvent event) { 356 mTempRect.setEmpty(); 357 358 if (!canScroll()) { 359 if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) { 360 View currentFocused = findFocus(); 361 if (currentFocused == this) currentFocused = null; 362 View nextFocused = FocusFinder.getInstance().findNextFocus(this, 363 currentFocused, View.FOCUS_DOWN); 364 return nextFocused != null 365 && nextFocused != this 366 && nextFocused.requestFocus(View.FOCUS_DOWN); 367 } 368 return false; 369 } 370 371 boolean handled = false; 372 if (event.getAction() == KeyEvent.ACTION_DOWN) { 373 switch (event.getKeyCode()) { 374 case KeyEvent.KEYCODE_DPAD_UP: 375 if (!event.isAltPressed()) { 376 handled = arrowScroll(View.FOCUS_UP); 377 } else { 378 handled = fullScroll(View.FOCUS_UP); 379 } 380 break; 381 case KeyEvent.KEYCODE_DPAD_DOWN: 382 if (!event.isAltPressed()) { 383 handled = arrowScroll(View.FOCUS_DOWN); 384 } else { 385 handled = fullScroll(View.FOCUS_DOWN); 386 } 387 break; 388 case KeyEvent.KEYCODE_SPACE: 389 pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN); 390 break; 391 } 392 } 393 394 return handled; 395 } 396 397 private boolean inChild(int x, int y) { 398 if (getChildCount() > 0) { 399 final int scrollY = mScrollY; 400 final View child = getChildAt(0); 401 return !(y < child.getTop() - scrollY 402 || y >= child.getBottom() - scrollY 403 || x < child.getLeft() 404 || x >= child.getRight()); 405 } 406 return false; 407 } 408 409 private void initOrResetVelocityTracker() { 410 if (mVelocityTracker == null) { 411 mVelocityTracker = VelocityTracker.obtain(); 412 } else { 413 mVelocityTracker.clear(); 414 } 415 } 416 417 private void initVelocityTrackerIfNotExists() { 418 if (mVelocityTracker == null) { 419 mVelocityTracker = VelocityTracker.obtain(); 420 } 421 } 422 423 private void recycleVelocityTracker() { 424 if (mVelocityTracker != null) { 425 mVelocityTracker.recycle(); 426 mVelocityTracker = null; 427 } 428 } 429 430 @Override 431 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 432 if (disallowIntercept) { 433 recycleVelocityTracker(); 434 } 435 super.requestDisallowInterceptTouchEvent(disallowIntercept); 436 } 437 438 439 @Override 440 public boolean onInterceptTouchEvent(MotionEvent ev) { 441 /* 442 * This method JUST determines whether we want to intercept the motion. 443 * If we return true, onMotionEvent will be called and we do the actual 444 * scrolling there. 445 */ 446 447 /* 448 * Shortcut the most recurring case: the user is in the dragging 449 * state and he is moving his finger. We want to intercept this 450 * motion. 451 */ 452 final int action = ev.getAction(); 453 if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { 454 return true; 455 } 456 457 switch (action & MotionEvent.ACTION_MASK) { 458 case MotionEvent.ACTION_MOVE: { 459 /* 460 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 461 * whether the user has moved far enough from his original down touch. 462 */ 463 464 /* 465 * Locally do absolute value. mLastMotionY is set to the y value 466 * of the down event. 467 */ 468 final int activePointerId = mActivePointerId; 469 if (activePointerId == INVALID_POINTER) { 470 // If we don't have a valid id, the touch down wasn't on content. 471 break; 472 } 473 474 final int pointerIndex = ev.findPointerIndex(activePointerId); 475 final float y = ev.getY(pointerIndex); 476 final int yDiff = (int) Math.abs(y - mLastMotionY); 477 if (yDiff > mTouchSlop) { 478 mIsBeingDragged = true; 479 mLastMotionY = y; 480 initVelocityTrackerIfNotExists(); 481 mVelocityTracker.addMovement(ev); 482 if (mScrollStrictSpan == null) { 483 mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll"); 484 } 485 } 486 break; 487 } 488 489 case MotionEvent.ACTION_DOWN: { 490 final float y = ev.getY(); 491 if (!inChild((int) ev.getX(), (int) y)) { 492 mIsBeingDragged = false; 493 recycleVelocityTracker(); 494 break; 495 } 496 497 /* 498 * Remember location of down touch. 499 * ACTION_DOWN always refers to pointer index 0. 500 */ 501 mLastMotionY = y; 502 mActivePointerId = ev.getPointerId(0); 503 504 initOrResetVelocityTracker(); 505 mVelocityTracker.addMovement(ev); 506 /* 507 * If being flinged and user touches the screen, initiate drag; 508 * otherwise don't. mScroller.isFinished should be false when 509 * being flinged. 510 */ 511 mIsBeingDragged = !mScroller.isFinished(); 512 if (mIsBeingDragged && mScrollStrictSpan == null) { 513 mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll"); 514 } 515 break; 516 } 517 518 case MotionEvent.ACTION_CANCEL: 519 case MotionEvent.ACTION_UP: 520 /* Release the drag */ 521 mIsBeingDragged = false; 522 mActivePointerId = INVALID_POINTER; 523 recycleVelocityTracker(); 524 if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) { 525 invalidate(); 526 } 527 break; 528 case MotionEvent.ACTION_POINTER_UP: 529 onSecondaryPointerUp(ev); 530 break; 531 } 532 533 /* 534 * The only time we want to intercept motion events is if we are in the 535 * drag mode. 536 */ 537 return mIsBeingDragged; 538 } 539 540 @Override 541 public boolean onTouchEvent(MotionEvent ev) { 542 initVelocityTrackerIfNotExists(); 543 mVelocityTracker.addMovement(ev); 544 545 final int action = ev.getAction(); 546 547 switch (action & MotionEvent.ACTION_MASK) { 548 case MotionEvent.ACTION_DOWN: { 549 mIsBeingDragged = getChildCount() != 0; 550 if (!mIsBeingDragged) { 551 return false; 552 } 553 554 /* 555 * If being flinged and user touches, stop the fling. isFinished 556 * will be false if being flinged. 557 */ 558 if (!mScroller.isFinished()) { 559 mScroller.abortAnimation(); 560 if (mFlingStrictSpan != null) { 561 mFlingStrictSpan.finish(); 562 mFlingStrictSpan = null; 563 } 564 } 565 566 // Remember where the motion event started 567 mLastMotionY = ev.getY(); 568 mActivePointerId = ev.getPointerId(0); 569 break; 570 } 571 case MotionEvent.ACTION_MOVE: 572 if (mIsBeingDragged) { 573 // Scroll to follow the motion event 574 final int activePointerIndex = ev.findPointerIndex(mActivePointerId); 575 final float y = ev.getY(activePointerIndex); 576 final int deltaY = (int) (mLastMotionY - y); 577 mLastMotionY = y; 578 579 final int oldX = mScrollX; 580 final int oldY = mScrollY; 581 final int range = getScrollRange(); 582 final int overscrollMode = getOverScrollMode(); 583 final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS || 584 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); 585 586 if (overScrollBy(0, deltaY, 0, mScrollY, 587 0, range, 0, mOverscrollDistance, true)) { 588 // Break our velocity if we hit a scroll barrier. 589 mVelocityTracker.clear(); 590 } 591 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 592 593 if (canOverscroll) { 594 final int pulledToY = oldY + deltaY; 595 if (pulledToY < 0) { 596 mEdgeGlowTop.onPull((float) deltaY / getHeight()); 597 if (!mEdgeGlowBottom.isFinished()) { 598 mEdgeGlowBottom.onRelease(); 599 } 600 } else if (pulledToY > range) { 601 mEdgeGlowBottom.onPull((float) deltaY / getHeight()); 602 if (!mEdgeGlowTop.isFinished()) { 603 mEdgeGlowTop.onRelease(); 604 } 605 } 606 if (mEdgeGlowTop != null 607 && (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) { 608 invalidate(); 609 } 610 } 611 } 612 break; 613 case MotionEvent.ACTION_UP: 614 if (mIsBeingDragged) { 615 final VelocityTracker velocityTracker = mVelocityTracker; 616 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 617 int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId); 618 619 if (getChildCount() > 0) { 620 if ((Math.abs(initialVelocity) > mMinimumVelocity)) { 621 fling(-initialVelocity); 622 } else { 623 if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, 624 getScrollRange())) { 625 invalidate(); 626 } 627 } 628 } 629 630 mActivePointerId = INVALID_POINTER; 631 endDrag(); 632 } 633 break; 634 case MotionEvent.ACTION_CANCEL: 635 if (mIsBeingDragged && getChildCount() > 0) { 636 if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) { 637 invalidate(); 638 } 639 mActivePointerId = INVALID_POINTER; 640 endDrag(); 641 } 642 break; 643 case MotionEvent.ACTION_POINTER_DOWN: { 644 final int index = ev.getActionIndex(); 645 mLastMotionY = ev.getY(index); 646 mActivePointerId = ev.getPointerId(index); 647 break; 648 } 649 case MotionEvent.ACTION_POINTER_UP: 650 onSecondaryPointerUp(ev); 651 mLastMotionY = ev.getY(ev.findPointerIndex(mActivePointerId)); 652 break; 653 } 654 return true; 655 } 656 657 private void onSecondaryPointerUp(MotionEvent ev) { 658 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> 659 MotionEvent.ACTION_POINTER_INDEX_SHIFT; 660 final int pointerId = ev.getPointerId(pointerIndex); 661 if (pointerId == mActivePointerId) { 662 // This was our active pointer going up. Choose a new 663 // active pointer and adjust accordingly. 664 // TODO: Make this decision more intelligent. 665 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 666 mLastMotionY = ev.getY(newPointerIndex); 667 mActivePointerId = ev.getPointerId(newPointerIndex); 668 if (mVelocityTracker != null) { 669 mVelocityTracker.clear(); 670 } 671 } 672 } 673 674 @Override 675 public boolean onGenericMotionEvent(MotionEvent event) { 676 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 677 switch (event.getAction()) { 678 case MotionEvent.ACTION_SCROLL: { 679 if (!mIsBeingDragged) { 680 final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); 681 if (vscroll != 0) { 682 final int delta = (int) (vscroll * getVerticalScrollFactor()); 683 final int range = getScrollRange(); 684 int oldScrollY = mScrollY; 685 int newScrollY = oldScrollY - delta; 686 if (newScrollY < 0) { 687 newScrollY = 0; 688 } else if (newScrollY > range) { 689 newScrollY = range; 690 } 691 if (newScrollY != oldScrollY) { 692 super.scrollTo(mScrollX, newScrollY); 693 return true; 694 } 695 } 696 } 697 } 698 } 699 } 700 return super.onGenericMotionEvent(event); 701 } 702 703 @Override 704 protected void onOverScrolled(int scrollX, int scrollY, 705 boolean clampedX, boolean clampedY) { 706 // Treat animating scrolls differently; see #computeScroll() for why. 707 if (!mScroller.isFinished()) { 708 mScrollX = scrollX; 709 mScrollY = scrollY; 710 invalidateParentIfNeeded(); 711 if (clampedY) { 712 mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange()); 713 } 714 } else { 715 super.scrollTo(scrollX, scrollY); 716 } 717 718 if (!awakenScrollBars()) { 719 invalidate(); 720 } 721 } 722 723 @Override 724 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 725 super.onInitializeAccessibilityNodeInfo(info); 726 info.setClassName(ScrollView.class.getName()); 727 info.setScrollable(getScrollRange() > 0); 728 } 729 730 @Override 731 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 732 super.onInitializeAccessibilityEvent(event); 733 event.setClassName(ScrollView.class.getName()); 734 final boolean scrollable = getScrollRange() > 0; 735 event.setScrollable(scrollable); 736 event.setScrollX(mScrollX); 737 event.setScrollY(mScrollY); 738 event.setMaxScrollX(mScrollX); 739 event.setMaxScrollY(getScrollRange()); 740 } 741 742 private int getScrollRange() { 743 int scrollRange = 0; 744 if (getChildCount() > 0) { 745 View child = getChildAt(0); 746 scrollRange = Math.max(0, 747 child.getHeight() - (getHeight() - mPaddingBottom - mPaddingTop)); 748 } 749 return scrollRange; 750 } 751 752 /** 753 * <p> 754 * Finds the next focusable component that fits in the specified bounds. 755 * </p> 756 * 757 * @param topFocus look for a candidate is the one at the top of the bounds 758 * if topFocus is true, or at the bottom of the bounds if topFocus is 759 * false 760 * @param top the top offset of the bounds in which a focusable must be 761 * found 762 * @param bottom the bottom offset of the bounds in which a focusable must 763 * be found 764 * @return the next focusable component in the bounds or null if none can 765 * be found 766 */ 767 private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) { 768 769 List<View> focusables = getFocusables(View.FOCUS_FORWARD); 770 View focusCandidate = null; 771 772 /* 773 * A fully contained focusable is one where its top is below the bound's 774 * top, and its bottom is above the bound's bottom. A partially 775 * contained focusable is one where some part of it is within the 776 * bounds, but it also has some part that is not within bounds. A fully contained 777 * focusable is preferred to a partially contained focusable. 778 */ 779 boolean foundFullyContainedFocusable = false; 780 781 int count = focusables.size(); 782 for (int i = 0; i < count; i++) { 783 View view = focusables.get(i); 784 int viewTop = view.getTop(); 785 int viewBottom = view.getBottom(); 786 787 if (top < viewBottom && viewTop < bottom) { 788 /* 789 * the focusable is in the target area, it is a candidate for 790 * focusing 791 */ 792 793 final boolean viewIsFullyContained = (top < viewTop) && 794 (viewBottom < bottom); 795 796 if (focusCandidate == null) { 797 /* No candidate, take this one */ 798 focusCandidate = view; 799 foundFullyContainedFocusable = viewIsFullyContained; 800 } else { 801 final boolean viewIsCloserToBoundary = 802 (topFocus && viewTop < focusCandidate.getTop()) || 803 (!topFocus && viewBottom > focusCandidate 804 .getBottom()); 805 806 if (foundFullyContainedFocusable) { 807 if (viewIsFullyContained && viewIsCloserToBoundary) { 808 /* 809 * We're dealing with only fully contained views, so 810 * it has to be closer to the boundary to beat our 811 * candidate 812 */ 813 focusCandidate = view; 814 } 815 } else { 816 if (viewIsFullyContained) { 817 /* Any fully contained view beats a partially contained view */ 818 focusCandidate = view; 819 foundFullyContainedFocusable = true; 820 } else if (viewIsCloserToBoundary) { 821 /* 822 * Partially contained view beats another partially 823 * contained view if it's closer 824 */ 825 focusCandidate = view; 826 } 827 } 828 } 829 } 830 } 831 832 return focusCandidate; 833 } 834 835 /** 836 * <p>Handles scrolling in response to a "page up/down" shortcut press. This 837 * method will scroll the view by one page up or down and give the focus 838 * to the topmost/bottommost component in the new visible area. If no 839 * component is a good candidate for focus, this scrollview reclaims the 840 * focus.</p> 841 * 842 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 843 * to go one page up or 844 * {@link android.view.View#FOCUS_DOWN} to go one page down 845 * @return true if the key event is consumed by this method, false otherwise 846 */ 847 public boolean pageScroll(int direction) { 848 boolean down = direction == View.FOCUS_DOWN; 849 int height = getHeight(); 850 851 if (down) { 852 mTempRect.top = getScrollY() + height; 853 int count = getChildCount(); 854 if (count > 0) { 855 View view = getChildAt(count - 1); 856 if (mTempRect.top + height > view.getBottom()) { 857 mTempRect.top = view.getBottom() - height; 858 } 859 } 860 } else { 861 mTempRect.top = getScrollY() - height; 862 if (mTempRect.top < 0) { 863 mTempRect.top = 0; 864 } 865 } 866 mTempRect.bottom = mTempRect.top + height; 867 868 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 869 } 870 871 /** 872 * <p>Handles scrolling in response to a "home/end" shortcut press. This 873 * method will scroll the view to the top or bottom and give the focus 874 * to the topmost/bottommost component in the new visible area. If no 875 * component is a good candidate for focus, this scrollview reclaims the 876 * focus.</p> 877 * 878 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 879 * to go the top of the view or 880 * {@link android.view.View#FOCUS_DOWN} to go the bottom 881 * @return true if the key event is consumed by this method, false otherwise 882 */ 883 public boolean fullScroll(int direction) { 884 boolean down = direction == View.FOCUS_DOWN; 885 int height = getHeight(); 886 887 mTempRect.top = 0; 888 mTempRect.bottom = height; 889 890 if (down) { 891 int count = getChildCount(); 892 if (count > 0) { 893 View view = getChildAt(count - 1); 894 mTempRect.bottom = view.getBottom() + mPaddingBottom; 895 mTempRect.top = mTempRect.bottom - height; 896 } 897 } 898 899 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 900 } 901 902 /** 903 * <p>Scrolls the view to make the area defined by <code>top</code> and 904 * <code>bottom</code> visible. This method attempts to give the focus 905 * to a component visible in this area. If no component can be focused in 906 * the new visible area, the focus is reclaimed by this ScrollView.</p> 907 * 908 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 909 * to go upward, {@link android.view.View#FOCUS_DOWN} to downward 910 * @param top the top offset of the new area to be made visible 911 * @param bottom the bottom offset of the new area to be made visible 912 * @return true if the key event is consumed by this method, false otherwise 913 */ 914 private boolean scrollAndFocus(int direction, int top, int bottom) { 915 boolean handled = true; 916 917 int height = getHeight(); 918 int containerTop = getScrollY(); 919 int containerBottom = containerTop + height; 920 boolean up = direction == View.FOCUS_UP; 921 922 View newFocused = findFocusableViewInBounds(up, top, bottom); 923 if (newFocused == null) { 924 newFocused = this; 925 } 926 927 if (top >= containerTop && bottom <= containerBottom) { 928 handled = false; 929 } else { 930 int delta = up ? (top - containerTop) : (bottom - containerBottom); 931 doScrollY(delta); 932 } 933 934 if (newFocused != findFocus()) newFocused.requestFocus(direction); 935 936 return handled; 937 } 938 939 /** 940 * Handle scrolling in response to an up or down arrow click. 941 * 942 * @param direction The direction corresponding to the arrow key that was 943 * pressed 944 * @return True if we consumed the event, false otherwise 945 */ 946 public boolean arrowScroll(int direction) { 947 948 View currentFocused = findFocus(); 949 if (currentFocused == this) currentFocused = null; 950 951 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); 952 953 final int maxJump = getMaxScrollAmount(); 954 955 if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) { 956 nextFocused.getDrawingRect(mTempRect); 957 offsetDescendantRectToMyCoords(nextFocused, mTempRect); 958 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 959 doScrollY(scrollDelta); 960 nextFocused.requestFocus(direction); 961 } else { 962 // no new focus 963 int scrollDelta = maxJump; 964 965 if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { 966 scrollDelta = getScrollY(); 967 } else if (direction == View.FOCUS_DOWN) { 968 if (getChildCount() > 0) { 969 int daBottom = getChildAt(0).getBottom(); 970 int screenBottom = getScrollY() + getHeight() - mPaddingBottom; 971 if (daBottom - screenBottom < maxJump) { 972 scrollDelta = daBottom - screenBottom; 973 } 974 } 975 } 976 if (scrollDelta == 0) { 977 return false; 978 } 979 doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); 980 } 981 982 if (currentFocused != null && currentFocused.isFocused() 983 && isOffScreen(currentFocused)) { 984 // previously focused item still has focus and is off screen, give 985 // it up (take it back to ourselves) 986 // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are 987 // sure to 988 // get it) 989 final int descendantFocusability = getDescendantFocusability(); // save 990 setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); 991 requestFocus(); 992 setDescendantFocusability(descendantFocusability); // restore 993 } 994 return true; 995 } 996 997 /** 998 * @return whether the descendant of this scroll view is scrolled off 999 * screen. 1000 */ 1001 private boolean isOffScreen(View descendant) { 1002 return !isWithinDeltaOfScreen(descendant, 0, getHeight()); 1003 } 1004 1005 /** 1006 * @return whether the descendant of this scroll view is within delta 1007 * pixels of being on the screen. 1008 */ 1009 private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) { 1010 descendant.getDrawingRect(mTempRect); 1011 offsetDescendantRectToMyCoords(descendant, mTempRect); 1012 1013 return (mTempRect.bottom + delta) >= getScrollY() 1014 && (mTempRect.top - delta) <= (getScrollY() + height); 1015 } 1016 1017 /** 1018 * Smooth scroll by a Y delta 1019 * 1020 * @param delta the number of pixels to scroll by on the Y axis 1021 */ 1022 private void doScrollY(int delta) { 1023 if (delta != 0) { 1024 if (mSmoothScrollingEnabled) { 1025 smoothScrollBy(0, delta); 1026 } else { 1027 scrollBy(0, delta); 1028 } 1029 } 1030 } 1031 1032 /** 1033 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 1034 * 1035 * @param dx the number of pixels to scroll by on the X axis 1036 * @param dy the number of pixels to scroll by on the Y axis 1037 */ 1038 public final void smoothScrollBy(int dx, int dy) { 1039 if (getChildCount() == 0) { 1040 // Nothing to do. 1041 return; 1042 } 1043 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 1044 if (duration > ANIMATED_SCROLL_GAP) { 1045 final int height = getHeight() - mPaddingBottom - mPaddingTop; 1046 final int bottom = getChildAt(0).getHeight(); 1047 final int maxY = Math.max(0, bottom - height); 1048 final int scrollY = mScrollY; 1049 dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY; 1050 1051 mScroller.startScroll(mScrollX, scrollY, 0, dy); 1052 invalidate(); 1053 } else { 1054 if (!mScroller.isFinished()) { 1055 mScroller.abortAnimation(); 1056 if (mFlingStrictSpan != null) { 1057 mFlingStrictSpan.finish(); 1058 mFlingStrictSpan = null; 1059 } 1060 } 1061 scrollBy(dx, dy); 1062 } 1063 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 1064 } 1065 1066 /** 1067 * Like {@link #scrollTo}, but scroll smoothly instead of immediately. 1068 * 1069 * @param x the position where to scroll on the X axis 1070 * @param y the position where to scroll on the Y axis 1071 */ 1072 public final void smoothScrollTo(int x, int y) { 1073 smoothScrollBy(x - mScrollX, y - mScrollY); 1074 } 1075 1076 /** 1077 * <p>The scroll range of a scroll view is the overall height of all of its 1078 * children.</p> 1079 */ 1080 @Override 1081 protected int computeVerticalScrollRange() { 1082 final int count = getChildCount(); 1083 final int contentHeight = getHeight() - mPaddingBottom - mPaddingTop; 1084 if (count == 0) { 1085 return contentHeight; 1086 } 1087 1088 int scrollRange = getChildAt(0).getBottom(); 1089 final int scrollY = mScrollY; 1090 final int overscrollBottom = Math.max(0, scrollRange - contentHeight); 1091 if (scrollY < 0) { 1092 scrollRange -= scrollY; 1093 } else if (scrollY > overscrollBottom) { 1094 scrollRange += scrollY - overscrollBottom; 1095 } 1096 1097 return scrollRange; 1098 } 1099 1100 @Override 1101 protected int computeVerticalScrollOffset() { 1102 return Math.max(0, super.computeVerticalScrollOffset()); 1103 } 1104 1105 @Override 1106 protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { 1107 ViewGroup.LayoutParams lp = child.getLayoutParams(); 1108 1109 int childWidthMeasureSpec; 1110 int childHeightMeasureSpec; 1111 1112 childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft 1113 + mPaddingRight, lp.width); 1114 1115 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 1116 1117 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1118 } 1119 1120 @Override 1121 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 1122 int parentHeightMeasureSpec, int heightUsed) { 1123 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 1124 1125 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 1126 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 1127 + widthUsed, lp.width); 1128 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( 1129 lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED); 1130 1131 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1132 } 1133 1134 @Override 1135 public void computeScroll() { 1136 if (mScroller.computeScrollOffset()) { 1137 // This is called at drawing time by ViewGroup. We don't want to 1138 // re-show the scrollbars at this point, which scrollTo will do, 1139 // so we replicate most of scrollTo here. 1140 // 1141 // It's a little odd to call onScrollChanged from inside the drawing. 1142 // 1143 // It is, except when you remember that computeScroll() is used to 1144 // animate scrolling. So unless we want to defer the onScrollChanged() 1145 // until the end of the animated scrolling, we don't really have a 1146 // choice here. 1147 // 1148 // I agree. The alternative, which I think would be worse, is to post 1149 // something and tell the subclasses later. This is bad because there 1150 // will be a window where mScrollX/Y is different from what the app 1151 // thinks it is. 1152 // 1153 int oldX = mScrollX; 1154 int oldY = mScrollY; 1155 int x = mScroller.getCurrX(); 1156 int y = mScroller.getCurrY(); 1157 1158 if (oldX != x || oldY != y) { 1159 final int range = getScrollRange(); 1160 final int overscrollMode = getOverScrollMode(); 1161 final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS || 1162 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); 1163 1164 overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, range, 1165 0, mOverflingDistance, false); 1166 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 1167 1168 if (canOverscroll) { 1169 if (y < 0 && oldY >= 0) { 1170 mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity()); 1171 } else if (y > range && oldY <= range) { 1172 mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity()); 1173 } 1174 } 1175 } 1176 1177 if (!awakenScrollBars()) { 1178 // Keep on drawing until the animation has finished. 1179 invalidate(); 1180 } 1181 } else { 1182 if (mFlingStrictSpan != null) { 1183 mFlingStrictSpan.finish(); 1184 mFlingStrictSpan = null; 1185 } 1186 } 1187 } 1188 1189 /** 1190 * Scrolls the view to the given child. 1191 * 1192 * @param child the View to scroll to 1193 */ 1194 private void scrollToChild(View child) { 1195 child.getDrawingRect(mTempRect); 1196 1197 /* Offset from child's local coordinates to ScrollView coordinates */ 1198 offsetDescendantRectToMyCoords(child, mTempRect); 1199 1200 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1201 1202 if (scrollDelta != 0) { 1203 scrollBy(0, scrollDelta); 1204 } 1205 } 1206 1207 /** 1208 * If rect is off screen, scroll just enough to get it (or at least the 1209 * first screen size chunk of it) on screen. 1210 * 1211 * @param rect The rectangle. 1212 * @param immediate True to scroll immediately without animation 1213 * @return true if scrolling was performed 1214 */ 1215 private boolean scrollToChildRect(Rect rect, boolean immediate) { 1216 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); 1217 final boolean scroll = delta != 0; 1218 if (scroll) { 1219 if (immediate) { 1220 scrollBy(0, delta); 1221 } else { 1222 smoothScrollBy(0, delta); 1223 } 1224 } 1225 return scroll; 1226 } 1227 1228 /** 1229 * Compute the amount to scroll in the Y direction in order to get 1230 * a rectangle completely on the screen (or, if taller than the screen, 1231 * at least the first screen size chunk of it). 1232 * 1233 * @param rect The rect. 1234 * @return The scroll delta. 1235 */ 1236 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { 1237 if (getChildCount() == 0) return 0; 1238 1239 int height = getHeight(); 1240 int screenTop = getScrollY(); 1241 int screenBottom = screenTop + height; 1242 1243 int fadingEdge = getVerticalFadingEdgeLength(); 1244 1245 // leave room for top fading edge as long as rect isn't at very top 1246 if (rect.top > 0) { 1247 screenTop += fadingEdge; 1248 } 1249 1250 // leave room for bottom fading edge as long as rect isn't at very bottom 1251 if (rect.bottom < getChildAt(0).getHeight()) { 1252 screenBottom -= fadingEdge; 1253 } 1254 1255 int scrollYDelta = 0; 1256 1257 if (rect.bottom > screenBottom && rect.top > screenTop) { 1258 // need to move down to get it in view: move down just enough so 1259 // that the entire rectangle is in view (or at least the first 1260 // screen size chunk). 1261 1262 if (rect.height() > height) { 1263 // just enough to get screen size chunk on 1264 scrollYDelta += (rect.top - screenTop); 1265 } else { 1266 // get entire rect at bottom of screen 1267 scrollYDelta += (rect.bottom - screenBottom); 1268 } 1269 1270 // make sure we aren't scrolling beyond the end of our content 1271 int bottom = getChildAt(0).getBottom(); 1272 int distanceToBottom = bottom - screenBottom; 1273 scrollYDelta = Math.min(scrollYDelta, distanceToBottom); 1274 1275 } else if (rect.top < screenTop && rect.bottom < screenBottom) { 1276 // need to move up to get it in view: move up just enough so that 1277 // entire rectangle is in view (or at least the first screen 1278 // size chunk of it). 1279 1280 if (rect.height() > height) { 1281 // screen size chunk 1282 scrollYDelta -= (screenBottom - rect.bottom); 1283 } else { 1284 // entire rect at top 1285 scrollYDelta -= (screenTop - rect.top); 1286 } 1287 1288 // make sure we aren't scrolling any further than the top our content 1289 scrollYDelta = Math.max(scrollYDelta, -getScrollY()); 1290 } 1291 return scrollYDelta; 1292 } 1293 1294 @Override 1295 public void requestChildFocus(View child, View focused) { 1296 if (!mIsLayoutDirty) { 1297 scrollToChild(focused); 1298 } else { 1299 // The child may not be laid out yet, we can't compute the scroll yet 1300 mChildToScrollTo = focused; 1301 } 1302 super.requestChildFocus(child, focused); 1303 } 1304 1305 1306 /** 1307 * When looking for focus in children of a scroll view, need to be a little 1308 * more careful not to give focus to something that is scrolled off screen. 1309 * 1310 * This is more expensive than the default {@link android.view.ViewGroup} 1311 * implementation, otherwise this behavior might have been made the default. 1312 */ 1313 @Override 1314 protected boolean onRequestFocusInDescendants(int direction, 1315 Rect previouslyFocusedRect) { 1316 1317 // convert from forward / backward notation to up / down / left / right 1318 // (ugh). 1319 if (direction == View.FOCUS_FORWARD) { 1320 direction = View.FOCUS_DOWN; 1321 } else if (direction == View.FOCUS_BACKWARD) { 1322 direction = View.FOCUS_UP; 1323 } 1324 1325 final View nextFocus = previouslyFocusedRect == null ? 1326 FocusFinder.getInstance().findNextFocus(this, null, direction) : 1327 FocusFinder.getInstance().findNextFocusFromRect(this, 1328 previouslyFocusedRect, direction); 1329 1330 if (nextFocus == null) { 1331 return false; 1332 } 1333 1334 if (isOffScreen(nextFocus)) { 1335 return false; 1336 } 1337 1338 return nextFocus.requestFocus(direction, previouslyFocusedRect); 1339 } 1340 1341 @Override 1342 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 1343 boolean immediate) { 1344 // offset into coordinate space of this scroll view 1345 rectangle.offset(child.getLeft() - child.getScrollX(), 1346 child.getTop() - child.getScrollY()); 1347 1348 return scrollToChildRect(rectangle, immediate); 1349 } 1350 1351 @Override 1352 public void requestLayout() { 1353 mIsLayoutDirty = true; 1354 super.requestLayout(); 1355 } 1356 1357 @Override 1358 protected void onDetachedFromWindow() { 1359 super.onDetachedFromWindow(); 1360 1361 if (mScrollStrictSpan != null) { 1362 mScrollStrictSpan.finish(); 1363 mScrollStrictSpan = null; 1364 } 1365 if (mFlingStrictSpan != null) { 1366 mFlingStrictSpan.finish(); 1367 mFlingStrictSpan = null; 1368 } 1369 } 1370 1371 @Override 1372 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1373 super.onLayout(changed, l, t, r, b); 1374 mIsLayoutDirty = false; 1375 // Give a child focus if it needs it 1376 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { 1377 scrollToChild(mChildToScrollTo); 1378 } 1379 mChildToScrollTo = null; 1380 1381 // Calling this with the present values causes it to re-claim them 1382 scrollTo(mScrollX, mScrollY); 1383 } 1384 1385 @Override 1386 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1387 super.onSizeChanged(w, h, oldw, oldh); 1388 1389 View currentFocused = findFocus(); 1390 if (null == currentFocused || this == currentFocused) 1391 return; 1392 1393 // If the currently-focused view was visible on the screen when the 1394 // screen was at the old height, then scroll the screen to make that 1395 // view visible with the new screen height. 1396 if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) { 1397 currentFocused.getDrawingRect(mTempRect); 1398 offsetDescendantRectToMyCoords(currentFocused, mTempRect); 1399 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1400 doScrollY(scrollDelta); 1401 } 1402 } 1403 1404 /** 1405 * Return true if child is a descendant of parent, (or equal to the parent). 1406 */ 1407 private static boolean isViewDescendantOf(View child, View parent) { 1408 if (child == parent) { 1409 return true; 1410 } 1411 1412 final ViewParent theParent = child.getParent(); 1413 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 1414 } 1415 1416 /** 1417 * Fling the scroll view 1418 * 1419 * @param velocityY The initial velocity in the Y direction. Positive 1420 * numbers mean that the finger/cursor is moving down the screen, 1421 * which means we want to scroll towards the top. 1422 */ 1423 public void fling(int velocityY) { 1424 if (getChildCount() > 0) { 1425 int height = getHeight() - mPaddingBottom - mPaddingTop; 1426 int bottom = getChildAt(0).getHeight(); 1427 1428 mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0, 1429 Math.max(0, bottom - height), 0, height/2); 1430 1431 if (mFlingStrictSpan == null) { 1432 mFlingStrictSpan = StrictMode.enterCriticalSpan("ScrollView-fling"); 1433 } 1434 1435 invalidate(); 1436 } 1437 } 1438 1439 private void endDrag() { 1440 mIsBeingDragged = false; 1441 1442 recycleVelocityTracker(); 1443 1444 if (mEdgeGlowTop != null) { 1445 mEdgeGlowTop.onRelease(); 1446 mEdgeGlowBottom.onRelease(); 1447 } 1448 1449 if (mScrollStrictSpan != null) { 1450 mScrollStrictSpan.finish(); 1451 mScrollStrictSpan = null; 1452 } 1453 } 1454 1455 /** 1456 * {@inheritDoc} 1457 * 1458 * <p>This version also clamps the scrolling to the bounds of our child. 1459 */ 1460 @Override 1461 public void scrollTo(int x, int y) { 1462 // we rely on the fact the View.scrollBy calls scrollTo. 1463 if (getChildCount() > 0) { 1464 View child = getChildAt(0); 1465 x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); 1466 y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); 1467 if (x != mScrollX || y != mScrollY) { 1468 super.scrollTo(x, y); 1469 } 1470 } 1471 } 1472 1473 @Override 1474 public void setOverScrollMode(int mode) { 1475 if (mode != OVER_SCROLL_NEVER) { 1476 if (mEdgeGlowTop == null) { 1477 Context context = getContext(); 1478 mEdgeGlowTop = new EdgeEffect(context); 1479 mEdgeGlowBottom = new EdgeEffect(context); 1480 } 1481 } else { 1482 mEdgeGlowTop = null; 1483 mEdgeGlowBottom = null; 1484 } 1485 super.setOverScrollMode(mode); 1486 } 1487 1488 @Override 1489 public void draw(Canvas canvas) { 1490 super.draw(canvas); 1491 if (mEdgeGlowTop != null) { 1492 final int scrollY = mScrollY; 1493 if (!mEdgeGlowTop.isFinished()) { 1494 final int restoreCount = canvas.save(); 1495 final int width = getWidth() - mPaddingLeft - mPaddingRight; 1496 1497 canvas.translate(mPaddingLeft, Math.min(0, scrollY)); 1498 mEdgeGlowTop.setSize(width, getHeight()); 1499 if (mEdgeGlowTop.draw(canvas)) { 1500 invalidate(); 1501 } 1502 canvas.restoreToCount(restoreCount); 1503 } 1504 if (!mEdgeGlowBottom.isFinished()) { 1505 final int restoreCount = canvas.save(); 1506 final int width = getWidth() - mPaddingLeft - mPaddingRight; 1507 final int height = getHeight(); 1508 1509 canvas.translate(-width + mPaddingLeft, 1510 Math.max(getScrollRange(), scrollY) + height); 1511 canvas.rotate(180, width, 0); 1512 mEdgeGlowBottom.setSize(width, height); 1513 if (mEdgeGlowBottom.draw(canvas)) { 1514 invalidate(); 1515 } 1516 canvas.restoreToCount(restoreCount); 1517 } 1518 } 1519 } 1520 1521 private static int clamp(int n, int my, int child) { 1522 if (my >= child || n < 0) { 1523 /* my >= child is this case: 1524 * |--------------- me ---------------| 1525 * |------ child ------| 1526 * or 1527 * |--------------- me ---------------| 1528 * |------ child ------| 1529 * or 1530 * |--------------- me ---------------| 1531 * |------ child ------| 1532 * 1533 * n < 0 is this case: 1534 * |------ me ------| 1535 * |-------- child --------| 1536 * |-- mScrollX --| 1537 */ 1538 return 0; 1539 } 1540 if ((my+n) > child) { 1541 /* this case: 1542 * |------ me ------| 1543 * |------ child ------| 1544 * |-- mScrollX --| 1545 */ 1546 return child-my; 1547 } 1548 return n; 1549 } 1550} 1551