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