ScrollView.java revision fb75738ee28839c67bef4abc15d6c7a407c34f55
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 if (clampedY) { 648 mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange()); 649 } 650 } else { 651 super.scrollTo(scrollX, scrollY); 652 } 653 awakenScrollBars(); 654 } 655 656 private int getScrollRange() { 657 int scrollRange = 0; 658 if (getChildCount() > 0) { 659 View child = getChildAt(0); 660 scrollRange = Math.max(0, 661 child.getHeight() - (getHeight() - mPaddingBottom - mPaddingTop)); 662 } 663 return scrollRange; 664 } 665 666 /** 667 * <p> 668 * Finds the next focusable component that fits in this View's bounds 669 * (excluding fading edges) pretending that this View's top is located at 670 * the parameter top. 671 * </p> 672 * 673 * @param topFocus look for a candidate is the one at the top of the bounds 674 * if topFocus is true, or at the bottom of the bounds if topFocus is 675 * false 676 * @param top the top offset of the bounds in which a focusable must be 677 * found (the fading edge is assumed to start at this position) 678 * @param preferredFocusable the View that has highest priority and will be 679 * returned if it is within my bounds (null is valid) 680 * @return the next focusable component in the bounds or null if none can be 681 * found 682 */ 683 private View findFocusableViewInMyBounds(final boolean topFocus, 684 final int top, View preferredFocusable) { 685 /* 686 * The fading edge's transparent side should be considered for focus 687 * since it's mostly visible, so we divide the actual fading edge length 688 * by 2. 689 */ 690 final int fadingEdgeLength = getVerticalFadingEdgeLength() / 2; 691 final int topWithoutFadingEdge = top + fadingEdgeLength; 692 final int bottomWithoutFadingEdge = top + getHeight() - fadingEdgeLength; 693 694 if ((preferredFocusable != null) 695 && (preferredFocusable.getTop() < bottomWithoutFadingEdge) 696 && (preferredFocusable.getBottom() > topWithoutFadingEdge)) { 697 return preferredFocusable; 698 } 699 700 return findFocusableViewInBounds(topFocus, topWithoutFadingEdge, 701 bottomWithoutFadingEdge); 702 } 703 704 /** 705 * <p> 706 * Finds the next focusable component that fits in the specified bounds. 707 * </p> 708 * 709 * @param topFocus look for a candidate is the one at the top of the bounds 710 * if topFocus is true, or at the bottom of the bounds if topFocus is 711 * false 712 * @param top the top offset of the bounds in which a focusable must be 713 * found 714 * @param bottom the bottom offset of the bounds in which a focusable must 715 * be found 716 * @return the next focusable component in the bounds or null if none can 717 * be found 718 */ 719 private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) { 720 721 List<View> focusables = getFocusables(View.FOCUS_FORWARD); 722 View focusCandidate = null; 723 724 /* 725 * A fully contained focusable is one where its top is below the bound's 726 * top, and its bottom is above the bound's bottom. A partially 727 * contained focusable is one where some part of it is within the 728 * bounds, but it also has some part that is not within bounds. A fully contained 729 * focusable is preferred to a partially contained focusable. 730 */ 731 boolean foundFullyContainedFocusable = false; 732 733 int count = focusables.size(); 734 for (int i = 0; i < count; i++) { 735 View view = focusables.get(i); 736 int viewTop = view.getTop(); 737 int viewBottom = view.getBottom(); 738 739 if (top < viewBottom && viewTop < bottom) { 740 /* 741 * the focusable is in the target area, it is a candidate for 742 * focusing 743 */ 744 745 final boolean viewIsFullyContained = (top < viewTop) && 746 (viewBottom < bottom); 747 748 if (focusCandidate == null) { 749 /* No candidate, take this one */ 750 focusCandidate = view; 751 foundFullyContainedFocusable = viewIsFullyContained; 752 } else { 753 final boolean viewIsCloserToBoundary = 754 (topFocus && viewTop < focusCandidate.getTop()) || 755 (!topFocus && viewBottom > focusCandidate 756 .getBottom()); 757 758 if (foundFullyContainedFocusable) { 759 if (viewIsFullyContained && viewIsCloserToBoundary) { 760 /* 761 * We're dealing with only fully contained views, so 762 * it has to be closer to the boundary to beat our 763 * candidate 764 */ 765 focusCandidate = view; 766 } 767 } else { 768 if (viewIsFullyContained) { 769 /* Any fully contained view beats a partially contained view */ 770 focusCandidate = view; 771 foundFullyContainedFocusable = true; 772 } else if (viewIsCloserToBoundary) { 773 /* 774 * Partially contained view beats another partially 775 * contained view if it's closer 776 */ 777 focusCandidate = view; 778 } 779 } 780 } 781 } 782 } 783 784 return focusCandidate; 785 } 786 787 /** 788 * <p>Handles scrolling in response to a "page up/down" shortcut press. This 789 * method will scroll the view by one page up or down and give the focus 790 * to the topmost/bottommost component in the new visible area. If no 791 * component is a good candidate for focus, this scrollview reclaims the 792 * focus.</p> 793 * 794 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 795 * to go one page up or 796 * {@link android.view.View#FOCUS_DOWN} to go one page down 797 * @return true if the key event is consumed by this method, false otherwise 798 */ 799 public boolean pageScroll(int direction) { 800 boolean down = direction == View.FOCUS_DOWN; 801 int height = getHeight(); 802 803 if (down) { 804 mTempRect.top = getScrollY() + height; 805 int count = getChildCount(); 806 if (count > 0) { 807 View view = getChildAt(count - 1); 808 if (mTempRect.top + height > view.getBottom()) { 809 mTempRect.top = view.getBottom() - height; 810 } 811 } 812 } else { 813 mTempRect.top = getScrollY() - height; 814 if (mTempRect.top < 0) { 815 mTempRect.top = 0; 816 } 817 } 818 mTempRect.bottom = mTempRect.top + height; 819 820 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 821 } 822 823 /** 824 * <p>Handles scrolling in response to a "home/end" shortcut press. This 825 * method will scroll the view to the top or bottom and give the focus 826 * to the topmost/bottommost component in the new visible area. If no 827 * component is a good candidate for focus, this scrollview reclaims the 828 * focus.</p> 829 * 830 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 831 * to go the top of the view or 832 * {@link android.view.View#FOCUS_DOWN} to go the bottom 833 * @return true if the key event is consumed by this method, false otherwise 834 */ 835 public boolean fullScroll(int direction) { 836 boolean down = direction == View.FOCUS_DOWN; 837 int height = getHeight(); 838 839 mTempRect.top = 0; 840 mTempRect.bottom = height; 841 842 if (down) { 843 int count = getChildCount(); 844 if (count > 0) { 845 View view = getChildAt(count - 1); 846 mTempRect.bottom = view.getBottom(); 847 mTempRect.top = mTempRect.bottom - height; 848 } 849 } 850 851 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 852 } 853 854 /** 855 * <p>Scrolls the view to make the area defined by <code>top</code> and 856 * <code>bottom</code> visible. This method attempts to give the focus 857 * to a component visible in this area. If no component can be focused in 858 * the new visible area, the focus is reclaimed by this scrollview.</p> 859 * 860 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 861 * to go upward 862 * {@link android.view.View#FOCUS_DOWN} to downward 863 * @param top the top offset of the new area to be made visible 864 * @param bottom the bottom offset of the new area to be made visible 865 * @return true if the key event is consumed by this method, false otherwise 866 */ 867 private boolean scrollAndFocus(int direction, int top, int bottom) { 868 boolean handled = true; 869 870 int height = getHeight(); 871 int containerTop = getScrollY(); 872 int containerBottom = containerTop + height; 873 boolean up = direction == View.FOCUS_UP; 874 875 View newFocused = findFocusableViewInBounds(up, top, bottom); 876 if (newFocused == null) { 877 newFocused = this; 878 } 879 880 if (top >= containerTop && bottom <= containerBottom) { 881 handled = false; 882 } else { 883 int delta = up ? (top - containerTop) : (bottom - containerBottom); 884 doScrollY(delta); 885 } 886 887 if (newFocused != findFocus() && newFocused.requestFocus(direction)) { 888 mScrollViewMovedFocus = true; 889 mScrollViewMovedFocus = false; 890 } 891 892 return handled; 893 } 894 895 /** 896 * Handle scrolling in response to an up or down arrow click. 897 * 898 * @param direction The direction corresponding to the arrow key that was 899 * pressed 900 * @return True if we consumed the event, false otherwise 901 */ 902 public boolean arrowScroll(int direction) { 903 904 View currentFocused = findFocus(); 905 if (currentFocused == this) currentFocused = null; 906 907 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); 908 909 final int maxJump = getMaxScrollAmount(); 910 911 if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) { 912 nextFocused.getDrawingRect(mTempRect); 913 offsetDescendantRectToMyCoords(nextFocused, mTempRect); 914 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 915 doScrollY(scrollDelta); 916 nextFocused.requestFocus(direction); 917 } else { 918 // no new focus 919 int scrollDelta = maxJump; 920 921 if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { 922 scrollDelta = getScrollY(); 923 } else if (direction == View.FOCUS_DOWN) { 924 if (getChildCount() > 0) { 925 int daBottom = getChildAt(0).getBottom(); 926 927 int screenBottom = getScrollY() + getHeight(); 928 929 if (daBottom - screenBottom < maxJump) { 930 scrollDelta = daBottom - screenBottom; 931 } 932 } 933 } 934 if (scrollDelta == 0) { 935 return false; 936 } 937 doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); 938 } 939 940 if (currentFocused != null && currentFocused.isFocused() 941 && isOffScreen(currentFocused)) { 942 // previously focused item still has focus and is off screen, give 943 // it up (take it back to ourselves) 944 // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are 945 // sure to 946 // get it) 947 final int descendantFocusability = getDescendantFocusability(); // save 948 setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); 949 requestFocus(); 950 setDescendantFocusability(descendantFocusability); // restore 951 } 952 return true; 953 } 954 955 /** 956 * @return whether the descendant of this scroll view is scrolled off 957 * screen. 958 */ 959 private boolean isOffScreen(View descendant) { 960 return !isWithinDeltaOfScreen(descendant, 0, getHeight()); 961 } 962 963 /** 964 * @return whether the descendant of this scroll view is within delta 965 * pixels of being on the screen. 966 */ 967 private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) { 968 descendant.getDrawingRect(mTempRect); 969 offsetDescendantRectToMyCoords(descendant, mTempRect); 970 971 return (mTempRect.bottom + delta) >= getScrollY() 972 && (mTempRect.top - delta) <= (getScrollY() + height); 973 } 974 975 /** 976 * Smooth scroll by a Y delta 977 * 978 * @param delta the number of pixels to scroll by on the Y axis 979 */ 980 private void doScrollY(int delta) { 981 if (delta != 0) { 982 if (mSmoothScrollingEnabled) { 983 smoothScrollBy(0, delta); 984 } else { 985 scrollBy(0, delta); 986 } 987 } 988 } 989 990 /** 991 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 992 * 993 * @param dx the number of pixels to scroll by on the X axis 994 * @param dy the number of pixels to scroll by on the Y axis 995 */ 996 public final void smoothScrollBy(int dx, int dy) { 997 if (getChildCount() == 0) { 998 // Nothing to do. 999 return; 1000 } 1001 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 1002 if (duration > ANIMATED_SCROLL_GAP) { 1003 final int height = getHeight() - mPaddingBottom - mPaddingTop; 1004 final int bottom = getChildAt(0).getHeight(); 1005 final int maxY = Math.max(0, bottom - height); 1006 final int scrollY = mScrollY; 1007 dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY; 1008 1009 mScroller.startScroll(mScrollX, scrollY, 0, dy); 1010 invalidate(); 1011 } else { 1012 if (!mScroller.isFinished()) { 1013 mScroller.abortAnimation(); 1014 if (mFlingStrictSpan != null) { 1015 mFlingStrictSpan.finish(); 1016 mFlingStrictSpan = null; 1017 } 1018 } 1019 scrollBy(dx, dy); 1020 } 1021 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 1022 } 1023 1024 /** 1025 * Like {@link #scrollTo}, but scroll smoothly instead of immediately. 1026 * 1027 * @param x the position where to scroll on the X axis 1028 * @param y the position where to scroll on the Y axis 1029 */ 1030 public final void smoothScrollTo(int x, int y) { 1031 smoothScrollBy(x - mScrollX, y - mScrollY); 1032 } 1033 1034 /** 1035 * <p>The scroll range of a scroll view is the overall height of all of its 1036 * children.</p> 1037 */ 1038 @Override 1039 protected int computeVerticalScrollRange() { 1040 final int count = getChildCount(); 1041 final int contentHeight = getHeight() - mPaddingBottom - mPaddingTop; 1042 if (count == 0) { 1043 return contentHeight; 1044 } 1045 1046 int scrollRange = getChildAt(0).getBottom(); 1047 final int scrollY = mScrollY; 1048 final int overscrollBottom = Math.max(0, scrollRange - contentHeight); 1049 if (scrollY < 0) { 1050 scrollRange -= scrollY; 1051 } else if (scrollY > overscrollBottom) { 1052 scrollRange += scrollY - overscrollBottom; 1053 } 1054 1055 return scrollRange; 1056 } 1057 1058 @Override 1059 protected int computeVerticalScrollOffset() { 1060 return Math.max(0, super.computeVerticalScrollOffset()); 1061 } 1062 1063 @Override 1064 protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { 1065 ViewGroup.LayoutParams lp = child.getLayoutParams(); 1066 1067 int childWidthMeasureSpec; 1068 int childHeightMeasureSpec; 1069 1070 childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft 1071 + mPaddingRight, lp.width); 1072 1073 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 1074 1075 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1076 } 1077 1078 @Override 1079 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 1080 int parentHeightMeasureSpec, int heightUsed) { 1081 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 1082 1083 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 1084 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 1085 + widthUsed, lp.width); 1086 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( 1087 lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED); 1088 1089 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1090 } 1091 1092 @Override 1093 public void computeScroll() { 1094 if (mScroller.computeScrollOffset()) { 1095 // This is called at drawing time by ViewGroup. We don't want to 1096 // re-show the scrollbars at this point, which scrollTo will do, 1097 // so we replicate most of scrollTo here. 1098 // 1099 // It's a little odd to call onScrollChanged from inside the drawing. 1100 // 1101 // It is, except when you remember that computeScroll() is used to 1102 // animate scrolling. So unless we want to defer the onScrollChanged() 1103 // until the end of the animated scrolling, we don't really have a 1104 // choice here. 1105 // 1106 // I agree. The alternative, which I think would be worse, is to post 1107 // something and tell the subclasses later. This is bad because there 1108 // will be a window where mScrollX/Y is different from what the app 1109 // thinks it is. 1110 // 1111 int oldX = mScrollX; 1112 int oldY = mScrollY; 1113 int x = mScroller.getCurrX(); 1114 int y = mScroller.getCurrY(); 1115 1116 if (oldX != x || oldY != y) { 1117 overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, getScrollRange(), 1118 0, mOverflingDistance, false); 1119 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 1120 1121 final int range = getScrollRange(); 1122 final int overscrollMode = getOverScrollMode(); 1123 if (overscrollMode == OVER_SCROLL_ALWAYS || 1124 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0)) { 1125 if (y < 0 && oldY >= 0) { 1126 mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity()); 1127 } else if (y > range && oldY <= range) { 1128 mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity()); 1129 } 1130 } 1131 } 1132 awakenScrollBars(); 1133 1134 // Keep on drawing until the animation has finished. 1135 postInvalidate(); 1136 } else { 1137 if (mFlingStrictSpan != null) { 1138 mFlingStrictSpan.finish(); 1139 mFlingStrictSpan = null; 1140 } 1141 } 1142 } 1143 1144 /** 1145 * Scrolls the view to the given child. 1146 * 1147 * @param child the View to scroll to 1148 */ 1149 private void scrollToChild(View child) { 1150 child.getDrawingRect(mTempRect); 1151 1152 /* Offset from child's local coordinates to ScrollView coordinates */ 1153 offsetDescendantRectToMyCoords(child, mTempRect); 1154 1155 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1156 1157 if (scrollDelta != 0) { 1158 scrollBy(0, scrollDelta); 1159 } 1160 } 1161 1162 /** 1163 * If rect is off screen, scroll just enough to get it (or at least the 1164 * first screen size chunk of it) on screen. 1165 * 1166 * @param rect The rectangle. 1167 * @param immediate True to scroll immediately without animation 1168 * @return true if scrolling was performed 1169 */ 1170 private boolean scrollToChildRect(Rect rect, boolean immediate) { 1171 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); 1172 final boolean scroll = delta != 0; 1173 if (scroll) { 1174 if (immediate) { 1175 scrollBy(0, delta); 1176 } else { 1177 smoothScrollBy(0, delta); 1178 } 1179 } 1180 return scroll; 1181 } 1182 1183 /** 1184 * Compute the amount to scroll in the Y direction in order to get 1185 * a rectangle completely on the screen (or, if taller than the screen, 1186 * at least the first screen size chunk of it). 1187 * 1188 * @param rect The rect. 1189 * @return The scroll delta. 1190 */ 1191 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { 1192 if (getChildCount() == 0) return 0; 1193 1194 int height = getHeight(); 1195 int screenTop = getScrollY(); 1196 int screenBottom = screenTop + height; 1197 1198 int fadingEdge = getVerticalFadingEdgeLength(); 1199 1200 // leave room for top fading edge as long as rect isn't at very top 1201 if (rect.top > 0) { 1202 screenTop += fadingEdge; 1203 } 1204 1205 // leave room for bottom fading edge as long as rect isn't at very bottom 1206 if (rect.bottom < getChildAt(0).getHeight()) { 1207 screenBottom -= fadingEdge; 1208 } 1209 1210 int scrollYDelta = 0; 1211 1212 if (rect.bottom > screenBottom && rect.top > screenTop) { 1213 // need to move down to get it in view: move down just enough so 1214 // that the entire rectangle is in view (or at least the first 1215 // screen size chunk). 1216 1217 if (rect.height() > height) { 1218 // just enough to get screen size chunk on 1219 scrollYDelta += (rect.top - screenTop); 1220 } else { 1221 // get entire rect at bottom of screen 1222 scrollYDelta += (rect.bottom - screenBottom); 1223 } 1224 1225 // make sure we aren't scrolling beyond the end of our content 1226 int bottom = getChildAt(0).getBottom(); 1227 int distanceToBottom = bottom - screenBottom; 1228 scrollYDelta = Math.min(scrollYDelta, distanceToBottom); 1229 1230 } else if (rect.top < screenTop && rect.bottom < screenBottom) { 1231 // need to move up to get it in view: move up just enough so that 1232 // entire rectangle is in view (or at least the first screen 1233 // size chunk of it). 1234 1235 if (rect.height() > height) { 1236 // screen size chunk 1237 scrollYDelta -= (screenBottom - rect.bottom); 1238 } else { 1239 // entire rect at top 1240 scrollYDelta -= (screenTop - rect.top); 1241 } 1242 1243 // make sure we aren't scrolling any further than the top our content 1244 scrollYDelta = Math.max(scrollYDelta, -getScrollY()); 1245 } 1246 return scrollYDelta; 1247 } 1248 1249 @Override 1250 public void requestChildFocus(View child, View focused) { 1251 if (!mScrollViewMovedFocus) { 1252 if (!mIsLayoutDirty) { 1253 scrollToChild(focused); 1254 } else { 1255 // The child may not be laid out yet, we can't compute the scroll yet 1256 mChildToScrollTo = focused; 1257 } 1258 } 1259 super.requestChildFocus(child, focused); 1260 } 1261 1262 1263 /** 1264 * When looking for focus in children of a scroll view, need to be a little 1265 * more careful not to give focus to something that is scrolled off screen. 1266 * 1267 * This is more expensive than the default {@link android.view.ViewGroup} 1268 * implementation, otherwise this behavior might have been made the default. 1269 */ 1270 @Override 1271 protected boolean onRequestFocusInDescendants(int direction, 1272 Rect previouslyFocusedRect) { 1273 1274 // convert from forward / backward notation to up / down / left / right 1275 // (ugh). 1276 if (direction == View.FOCUS_FORWARD) { 1277 direction = View.FOCUS_DOWN; 1278 } else if (direction == View.FOCUS_BACKWARD) { 1279 direction = View.FOCUS_UP; 1280 } 1281 1282 final View nextFocus = previouslyFocusedRect == null ? 1283 FocusFinder.getInstance().findNextFocus(this, null, direction) : 1284 FocusFinder.getInstance().findNextFocusFromRect(this, 1285 previouslyFocusedRect, direction); 1286 1287 if (nextFocus == null) { 1288 return false; 1289 } 1290 1291 if (isOffScreen(nextFocus)) { 1292 return false; 1293 } 1294 1295 return nextFocus.requestFocus(direction, previouslyFocusedRect); 1296 } 1297 1298 @Override 1299 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 1300 boolean immediate) { 1301 // offset into coordinate space of this scroll view 1302 rectangle.offset(child.getLeft() - child.getScrollX(), 1303 child.getTop() - child.getScrollY()); 1304 1305 return scrollToChildRect(rectangle, immediate); 1306 } 1307 1308 @Override 1309 public void requestLayout() { 1310 mIsLayoutDirty = true; 1311 super.requestLayout(); 1312 } 1313 1314 @Override 1315 protected void onDetachedFromWindow() { 1316 super.onDetachedFromWindow(); 1317 1318 if (mScrollStrictSpan != null) { 1319 mScrollStrictSpan.finish(); 1320 mScrollStrictSpan = null; 1321 } 1322 if (mFlingStrictSpan != null) { 1323 mFlingStrictSpan.finish(); 1324 mFlingStrictSpan = null; 1325 } 1326 } 1327 1328 @Override 1329 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1330 super.onLayout(changed, l, t, r, b); 1331 mIsLayoutDirty = false; 1332 // Give a child focus if it needs it 1333 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { 1334 scrollToChild(mChildToScrollTo); 1335 } 1336 mChildToScrollTo = null; 1337 1338 // Calling this with the present values causes it to re-clam them 1339 scrollTo(mScrollX, mScrollY); 1340 } 1341 1342 @Override 1343 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1344 super.onSizeChanged(w, h, oldw, oldh); 1345 1346 View currentFocused = findFocus(); 1347 if (null == currentFocused || this == currentFocused) 1348 return; 1349 1350 // If the currently-focused view was visible on the screen when the 1351 // screen was at the old height, then scroll the screen to make that 1352 // view visible with the new screen height. 1353 if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) { 1354 currentFocused.getDrawingRect(mTempRect); 1355 offsetDescendantRectToMyCoords(currentFocused, mTempRect); 1356 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1357 doScrollY(scrollDelta); 1358 } 1359 } 1360 1361 /** 1362 * Return true if child is an descendant of parent, (or equal to the parent). 1363 */ 1364 private boolean isViewDescendantOf(View child, View parent) { 1365 if (child == parent) { 1366 return true; 1367 } 1368 1369 final ViewParent theParent = child.getParent(); 1370 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 1371 } 1372 1373 /** 1374 * Fling the scroll view 1375 * 1376 * @param velocityY The initial velocity in the Y direction. Positive 1377 * numbers mean that the finger/cursor is moving down the screen, 1378 * which means we want to scroll towards the top. 1379 */ 1380 public void fling(int velocityY) { 1381 if (getChildCount() > 0) { 1382 int height = getHeight() - mPaddingBottom - mPaddingTop; 1383 int bottom = getChildAt(0).getHeight(); 1384 1385 mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0, 1386 Math.max(0, bottom - height), 0, height/2); 1387 1388 final boolean movingDown = velocityY > 0; 1389 1390 View newFocused = 1391 findFocusableViewInMyBounds(movingDown, mScroller.getFinalY(), findFocus()); 1392 if (newFocused == null) { 1393 newFocused = this; 1394 } 1395 1396 if (newFocused != findFocus() 1397 && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) { 1398 mScrollViewMovedFocus = true; 1399 mScrollViewMovedFocus = false; 1400 } 1401 1402 if (mFlingStrictSpan == null) { 1403 mFlingStrictSpan = StrictMode.enterCriticalSpan("ScrollView-fling"); 1404 } 1405 1406 invalidate(); 1407 } 1408 } 1409 1410 private void endDrag() { 1411 mIsBeingDragged = false; 1412 1413 if (mVelocityTracker != null) { 1414 mVelocityTracker.recycle(); 1415 mVelocityTracker = null; 1416 } 1417 1418 if (mEdgeGlowTop != null) { 1419 mEdgeGlowTop.onRelease(); 1420 mEdgeGlowBottom.onRelease(); 1421 } 1422 1423 if (mScrollStrictSpan != null) { 1424 mScrollStrictSpan.finish(); 1425 mScrollStrictSpan = null; 1426 } 1427 } 1428 1429 /** 1430 * {@inheritDoc} 1431 * 1432 * <p>This version also clamps the scrolling to the bounds of our child. 1433 */ 1434 @Override 1435 public void scrollTo(int x, int y) { 1436 // we rely on the fact the View.scrollBy calls scrollTo. 1437 if (getChildCount() > 0) { 1438 View child = getChildAt(0); 1439 x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); 1440 y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); 1441 if (x != mScrollX || y != mScrollY) { 1442 super.scrollTo(x, y); 1443 } 1444 } 1445 } 1446 1447 @Override 1448 public void setOverScrollMode(int mode) { 1449 if (mode != OVER_SCROLL_NEVER) { 1450 if (mEdgeGlowTop == null) { 1451 Context context = getContext(); 1452 final Resources res = context.getResources(); 1453 final Drawable edge = res.getDrawable(R.drawable.overscroll_edge); 1454 final Drawable glow = res.getDrawable(R.drawable.overscroll_glow); 1455 mEdgeGlowTop = new EdgeGlow(context, edge, glow); 1456 mEdgeGlowBottom = new EdgeGlow(context, edge, glow); 1457 } 1458 } else { 1459 mEdgeGlowTop = null; 1460 mEdgeGlowBottom = null; 1461 } 1462 super.setOverScrollMode(mode); 1463 } 1464 1465 @Override 1466 public void draw(Canvas canvas) { 1467 super.draw(canvas); 1468 if (mEdgeGlowTop != null) { 1469 final int scrollY = mScrollY; 1470 if (!mEdgeGlowTop.isFinished()) { 1471 final int restoreCount = canvas.save(); 1472 final int width = getWidth(); 1473 1474 canvas.translate(0, Math.min(0, scrollY)); 1475 mEdgeGlowTop.setSize(width, getHeight()); 1476 if (mEdgeGlowTop.draw(canvas)) { 1477 invalidate(); 1478 } 1479 canvas.restoreToCount(restoreCount); 1480 } 1481 if (!mEdgeGlowBottom.isFinished()) { 1482 final int restoreCount = canvas.save(); 1483 final int width = getWidth(); 1484 final int height = getHeight(); 1485 1486 canvas.translate(-width, Math.max(getScrollRange(), scrollY) + height); 1487 canvas.rotate(180, width, 0); 1488 mEdgeGlowBottom.setSize(width, height); 1489 if (mEdgeGlowBottom.draw(canvas)) { 1490 invalidate(); 1491 } 1492 canvas.restoreToCount(restoreCount); 1493 } 1494 } 1495 } 1496 1497 private int clamp(int n, int my, int child) { 1498 if (my >= child || n < 0) { 1499 /* my >= child is this case: 1500 * |--------------- me ---------------| 1501 * |------ child ------| 1502 * or 1503 * |--------------- me ---------------| 1504 * |------ child ------| 1505 * or 1506 * |--------------- me ---------------| 1507 * |------ child ------| 1508 * 1509 * n < 0 is this case: 1510 * |------ me ------| 1511 * |-------- child --------| 1512 * |-- mScrollX --| 1513 */ 1514 return 0; 1515 } 1516 if ((my+n) > child) { 1517 /* this case: 1518 * |------ me ------| 1519 * |------ child ------| 1520 * |-- mScrollX --| 1521 */ 1522 return child-my; 1523 } 1524 return n; 1525 } 1526} 1527