ScrollView.java revision 8202cd3602b87634eeb8b2729612d96f8dbf9416
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.widget; 18 19import com.android.internal.R; 20 21import android.content.Context; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Canvas; 25import android.graphics.Rect; 26import android.graphics.drawable.Drawable; 27import android.os.StrictMode; 28import android.util.AttributeSet; 29import android.view.FocusFinder; 30import android.view.InputDevice; 31import android.view.KeyEvent; 32import android.view.MotionEvent; 33import android.view.VelocityTracker; 34import android.view.View; 35import android.view.ViewConfiguration; 36import android.view.ViewDebug; 37import android.view.ViewGroup; 38import android.view.ViewParent; 39import android.view.accessibility.AccessibilityEvent; 40import android.view.accessibility.AccessibilityNodeInfo; 41import android.view.animation.AnimationUtils; 42 43import java.util.List; 44 45/** 46 * Layout container for a view hierarchy that can be scrolled by the user, 47 * allowing it to be larger than the physical display. A ScrollView 48 * is a {@link FrameLayout}, meaning you should place one child in it 49 * containing the entire contents to scroll; this child may itself be a layout 50 * manager with a complex hierarchy of objects. A child that is often used 51 * is a {@link LinearLayout} in a vertical orientation, presenting a vertical 52 * array of top-level items that the user can scroll through. 53 * 54 * <p>The {@link TextView} class also 55 * takes care of its own scrolling, so does not require a ScrollView, but 56 * using the two together is possible to achieve the effect of a text view 57 * within a larger container. 58 * 59 * <p>ScrollView only supports vertical scrolling. 60 * 61 * @attr ref android.R.styleable#ScrollView_fillViewport 62 */ 63public class ScrollView extends FrameLayout { 64 static final int ANIMATED_SCROLL_GAP = 250; 65 66 static final float MAX_SCROLL_FACTOR = 0.5f; 67 68 private long mLastScroll; 69 70 private final Rect mTempRect = new Rect(); 71 private OverScroller mScroller; 72 private EdgeGlow mEdgeGlowTop; 73 private EdgeGlow mEdgeGlowBottom; 74 75 /** 76 * Position of the last motion event. 77 */ 78 private float mLastMotionY; 79 80 /** 81 * True when the layout has changed but the traversal has not come through yet. 82 * Ideally the view hierarchy would keep track of this for us. 83 */ 84 private boolean mIsLayoutDirty = true; 85 86 /** 87 * The child to give focus to in the event that a child has requested focus while the 88 * layout is dirty. This prevents the scroll from being wrong if the child has not been 89 * laid out before requesting focus. 90 */ 91 private View mChildToScrollTo = null; 92 93 /** 94 * True if the user is currently dragging this ScrollView around. This is 95 * not the same as 'is being flinged', which can be checked by 96 * mScroller.isFinished() (flinging begins when the user lifts his finger). 97 */ 98 private boolean mIsBeingDragged = false; 99 100 /** 101 * Determines speed during touch scrolling 102 */ 103 private VelocityTracker mVelocityTracker; 104 105 /** 106 * When set to true, the scroll view measure its child to make it fill the currently 107 * visible area. 108 */ 109 @ViewDebug.ExportedProperty(category = "layout") 110 private boolean mFillViewport; 111 112 /** 113 * Whether arrow scrolling is animated. 114 */ 115 private boolean mSmoothScrollingEnabled = true; 116 117 private int mTouchSlop; 118 private int mMinimumVelocity; 119 private int mMaximumVelocity; 120 121 private int mOverscrollDistance; 122 private int mOverflingDistance; 123 124 /** 125 * ID of the active pointer. This is used to retain consistency during 126 * drags/flings if multiple pointers are used. 127 */ 128 private int mActivePointerId = INVALID_POINTER; 129 130 /** 131 * The StrictMode "critical time span" objects to catch animation 132 * stutters. Non-null when a time-sensitive animation is 133 * in-flight. Must call finish() on them when done animating. 134 * These are no-ops on user builds. 135 */ 136 private StrictMode.Span mScrollStrictSpan = null; // aka "drag" 137 private StrictMode.Span mFlingStrictSpan = null; 138 139 /** 140 * Sentinel value for no current active pointer. 141 * Used by {@link #mActivePointerId}. 142 */ 143 private static final int INVALID_POINTER = -1; 144 145 public ScrollView(Context context) { 146 this(context, null); 147 } 148 149 public ScrollView(Context context, AttributeSet attrs) { 150 this(context, attrs, com.android.internal.R.attr.scrollViewStyle); 151 } 152 153 public ScrollView(Context context, AttributeSet attrs, int defStyle) { 154 super(context, attrs, defStyle); 155 initScrollView(); 156 157 TypedArray a = 158 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ScrollView, defStyle, 0); 159 160 setFillViewport(a.getBoolean(R.styleable.ScrollView_fillViewport, false)); 161 162 a.recycle(); 163 } 164 165 @Override 166 public boolean shouldDelayChildPressedState() { 167 return true; 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_DOWN: { 617 final int index = ev.getActionIndex(); 618 final float y = ev.getY(index); 619 mLastMotionY = y; 620 mActivePointerId = ev.getPointerId(index); 621 break; 622 } 623 case MotionEvent.ACTION_POINTER_UP: 624 onSecondaryPointerUp(ev); 625 mLastMotionY = ev.getY(ev.findPointerIndex(mActivePointerId)); 626 break; 627 } 628 return true; 629 } 630 631 private void onSecondaryPointerUp(MotionEvent ev) { 632 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> 633 MotionEvent.ACTION_POINTER_INDEX_SHIFT; 634 final int pointerId = ev.getPointerId(pointerIndex); 635 if (pointerId == mActivePointerId) { 636 // This was our active pointer going up. Choose a new 637 // active pointer and adjust accordingly. 638 // TODO: Make this decision more intelligent. 639 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 640 mLastMotionY = ev.getY(newPointerIndex); 641 mActivePointerId = ev.getPointerId(newPointerIndex); 642 if (mVelocityTracker != null) { 643 mVelocityTracker.clear(); 644 } 645 } 646 } 647 648 @Override 649 public boolean onGenericMotionEvent(MotionEvent event) { 650 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 651 switch (event.getAction()) { 652 case MotionEvent.ACTION_SCROLL: { 653 if (!mIsBeingDragged) { 654 final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); 655 if (vscroll != 0) { 656 final int delta = (int) (vscroll * getVerticalScrollFactor()); 657 final int range = getScrollRange(); 658 int oldScrollY = mScrollY; 659 int newScrollY = oldScrollY - delta; 660 if (newScrollY < 0) { 661 newScrollY = 0; 662 } else if (newScrollY > range) { 663 newScrollY = range; 664 } 665 if (newScrollY != oldScrollY) { 666 super.scrollTo(mScrollX, newScrollY); 667 return true; 668 } 669 } 670 } 671 } 672 } 673 } 674 return super.onGenericMotionEvent(event); 675 } 676 677 @Override 678 protected void onOverScrolled(int scrollX, int scrollY, 679 boolean clampedX, boolean clampedY) { 680 // Treat animating scrolls differently; see #computeScroll() for why. 681 if (!mScroller.isFinished()) { 682 mScrollX = scrollX; 683 mScrollY = scrollY; 684 invalidateParentIfNeeded(); 685 if (clampedY) { 686 mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange()); 687 } 688 } else { 689 super.scrollTo(scrollX, scrollY); 690 } 691 awakenScrollBars(); 692 } 693 694 @Override 695 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 696 super.onInitializeAccessibilityNodeInfo(info); 697 info.setScrollable(true); 698 } 699 700 @Override 701 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 702 super.onInitializeAccessibilityEvent(event); 703 event.setScrollable(true); 704 } 705 706 @Override 707 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 708 // Do not append text content to scroll events they are fired frequently 709 // and the client has already received another event type with the text. 710 if (event.getEventType() != AccessibilityEvent.TYPE_VIEW_SCROLLED) { 711 super.dispatchPopulateAccessibilityEvent(event); 712 } 713 return false; 714 } 715 716 private int getScrollRange() { 717 int scrollRange = 0; 718 if (getChildCount() > 0) { 719 View child = getChildAt(0); 720 scrollRange = Math.max(0, 721 child.getHeight() - (getHeight() - mPaddingBottom - mPaddingTop)); 722 } 723 return scrollRange; 724 } 725 726 /** 727 * <p> 728 * Finds the next focusable component that fits in this View's bounds 729 * (excluding fading edges) pretending that this View's top is located at 730 * the parameter top. 731 * </p> 732 * 733 * @param topFocus look for a candidate at the top of the bounds if topFocus is true, 734 * or at the bottom of the bounds if topFocus is false 735 * @param top the top offset of the bounds in which a focusable must be 736 * found (the fading edge is assumed to start at this position) 737 * @param preferredFocusable the View that has highest priority and will be 738 * returned if it is within my bounds (null is valid) 739 * @return the next focusable component in the bounds or null if none can be found 740 */ 741 private View findFocusableViewInMyBounds(final boolean topFocus, 742 final int top, View preferredFocusable) { 743 /* 744 * The fading edge's transparent side should be considered for focus 745 * since it's mostly visible, so we divide the actual fading edge length 746 * by 2. 747 */ 748 final int fadingEdgeLength = getVerticalFadingEdgeLength() / 2; 749 final int topWithoutFadingEdge = top + fadingEdgeLength; 750 final int bottomWithoutFadingEdge = top + getHeight() - fadingEdgeLength; 751 752 if ((preferredFocusable != null) 753 && (preferredFocusable.getTop() < bottomWithoutFadingEdge) 754 && (preferredFocusable.getBottom() > topWithoutFadingEdge)) { 755 return preferredFocusable; 756 } 757 758 return findFocusableViewInBounds(topFocus, topWithoutFadingEdge, 759 bottomWithoutFadingEdge); 760 } 761 762 /** 763 * <p> 764 * Finds the next focusable component that fits in the specified bounds. 765 * </p> 766 * 767 * @param topFocus look for a candidate is the one at the top of the bounds 768 * if topFocus is true, or at the bottom of the bounds if topFocus is 769 * false 770 * @param top the top offset of the bounds in which a focusable must be 771 * found 772 * @param bottom the bottom offset of the bounds in which a focusable must 773 * be found 774 * @return the next focusable component in the bounds or null if none can 775 * be found 776 */ 777 private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) { 778 779 List<View> focusables = getFocusables(View.FOCUS_FORWARD); 780 View focusCandidate = null; 781 782 /* 783 * A fully contained focusable is one where its top is below the bound's 784 * top, and its bottom is above the bound's bottom. A partially 785 * contained focusable is one where some part of it is within the 786 * bounds, but it also has some part that is not within bounds. A fully contained 787 * focusable is preferred to a partially contained focusable. 788 */ 789 boolean foundFullyContainedFocusable = false; 790 791 int count = focusables.size(); 792 for (int i = 0; i < count; i++) { 793 View view = focusables.get(i); 794 int viewTop = view.getTop(); 795 int viewBottom = view.getBottom(); 796 797 if (top < viewBottom && viewTop < bottom) { 798 /* 799 * the focusable is in the target area, it is a candidate for 800 * focusing 801 */ 802 803 final boolean viewIsFullyContained = (top < viewTop) && 804 (viewBottom < bottom); 805 806 if (focusCandidate == null) { 807 /* No candidate, take this one */ 808 focusCandidate = view; 809 foundFullyContainedFocusable = viewIsFullyContained; 810 } else { 811 final boolean viewIsCloserToBoundary = 812 (topFocus && viewTop < focusCandidate.getTop()) || 813 (!topFocus && viewBottom > focusCandidate 814 .getBottom()); 815 816 if (foundFullyContainedFocusable) { 817 if (viewIsFullyContained && viewIsCloserToBoundary) { 818 /* 819 * We're dealing with only fully contained views, so 820 * it has to be closer to the boundary to beat our 821 * candidate 822 */ 823 focusCandidate = view; 824 } 825 } else { 826 if (viewIsFullyContained) { 827 /* Any fully contained view beats a partially contained view */ 828 focusCandidate = view; 829 foundFullyContainedFocusable = true; 830 } else if (viewIsCloserToBoundary) { 831 /* 832 * Partially contained view beats another partially 833 * contained view if it's closer 834 */ 835 focusCandidate = view; 836 } 837 } 838 } 839 } 840 } 841 842 return focusCandidate; 843 } 844 845 /** 846 * <p>Handles scrolling in response to a "page up/down" shortcut press. This 847 * method will scroll the view by one page up or down and give the focus 848 * to the topmost/bottommost component in the new visible area. If no 849 * component is a good candidate for focus, this scrollview reclaims the 850 * focus.</p> 851 * 852 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 853 * to go one page up or 854 * {@link android.view.View#FOCUS_DOWN} to go one page down 855 * @return true if the key event is consumed by this method, false otherwise 856 */ 857 public boolean pageScroll(int direction) { 858 boolean down = direction == View.FOCUS_DOWN; 859 int height = getHeight(); 860 861 if (down) { 862 mTempRect.top = getScrollY() + height; 863 int count = getChildCount(); 864 if (count > 0) { 865 View view = getChildAt(count - 1); 866 if (mTempRect.top + height > view.getBottom()) { 867 mTempRect.top = view.getBottom() - height; 868 } 869 } 870 } else { 871 mTempRect.top = getScrollY() - height; 872 if (mTempRect.top < 0) { 873 mTempRect.top = 0; 874 } 875 } 876 mTempRect.bottom = mTempRect.top + height; 877 878 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 879 } 880 881 /** 882 * <p>Handles scrolling in response to a "home/end" shortcut press. This 883 * method will scroll the view to the top or bottom and give the focus 884 * to the topmost/bottommost component in the new visible area. If no 885 * component is a good candidate for focus, this scrollview reclaims the 886 * focus.</p> 887 * 888 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 889 * to go the top of the view or 890 * {@link android.view.View#FOCUS_DOWN} to go the bottom 891 * @return true if the key event is consumed by this method, false otherwise 892 */ 893 public boolean fullScroll(int direction) { 894 boolean down = direction == View.FOCUS_DOWN; 895 int height = getHeight(); 896 897 mTempRect.top = 0; 898 mTempRect.bottom = height; 899 900 if (down) { 901 int count = getChildCount(); 902 if (count > 0) { 903 View view = getChildAt(count - 1); 904 mTempRect.bottom = view.getBottom() + mPaddingBottom; 905 mTempRect.top = mTempRect.bottom - height; 906 } 907 } 908 909 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 910 } 911 912 /** 913 * <p>Scrolls the view to make the area defined by <code>top</code> and 914 * <code>bottom</code> visible. This method attempts to give the focus 915 * to a component visible in this area. If no component can be focused in 916 * the new visible area, the focus is reclaimed by this ScrollView.</p> 917 * 918 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 919 * to go upward, {@link android.view.View#FOCUS_DOWN} to downward 920 * @param top the top offset of the new area to be made visible 921 * @param bottom the bottom offset of the new area to be made visible 922 * @return true if the key event is consumed by this method, false otherwise 923 */ 924 private boolean scrollAndFocus(int direction, int top, int bottom) { 925 boolean handled = true; 926 927 int height = getHeight(); 928 int containerTop = getScrollY(); 929 int containerBottom = containerTop + height; 930 boolean up = direction == View.FOCUS_UP; 931 932 View newFocused = findFocusableViewInBounds(up, top, bottom); 933 if (newFocused == null) { 934 newFocused = this; 935 } 936 937 if (top >= containerTop && bottom <= containerBottom) { 938 handled = false; 939 } else { 940 int delta = up ? (top - containerTop) : (bottom - containerBottom); 941 doScrollY(delta); 942 } 943 944 if (newFocused != findFocus()) newFocused.requestFocus(direction); 945 946 return handled; 947 } 948 949 /** 950 * Handle scrolling in response to an up or down arrow click. 951 * 952 * @param direction The direction corresponding to the arrow key that was 953 * pressed 954 * @return True if we consumed the event, false otherwise 955 */ 956 public boolean arrowScroll(int direction) { 957 958 View currentFocused = findFocus(); 959 if (currentFocused == this) currentFocused = null; 960 961 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); 962 963 final int maxJump = getMaxScrollAmount(); 964 965 if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) { 966 nextFocused.getDrawingRect(mTempRect); 967 offsetDescendantRectToMyCoords(nextFocused, mTempRect); 968 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 969 doScrollY(scrollDelta); 970 nextFocused.requestFocus(direction); 971 } else { 972 // no new focus 973 int scrollDelta = maxJump; 974 975 if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { 976 scrollDelta = getScrollY(); 977 } else if (direction == View.FOCUS_DOWN) { 978 if (getChildCount() > 0) { 979 int daBottom = getChildAt(0).getBottom(); 980 int screenBottom = getScrollY() + getHeight() - mPaddingBottom; 981 if (daBottom - screenBottom < maxJump) { 982 scrollDelta = daBottom - screenBottom; 983 } 984 } 985 } 986 if (scrollDelta == 0) { 987 return false; 988 } 989 doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); 990 } 991 992 if (currentFocused != null && currentFocused.isFocused() 993 && isOffScreen(currentFocused)) { 994 // previously focused item still has focus and is off screen, give 995 // it up (take it back to ourselves) 996 // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are 997 // sure to 998 // get it) 999 final int descendantFocusability = getDescendantFocusability(); // save 1000 setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); 1001 requestFocus(); 1002 setDescendantFocusability(descendantFocusability); // restore 1003 } 1004 return true; 1005 } 1006 1007 /** 1008 * @return whether the descendant of this scroll view is scrolled off 1009 * screen. 1010 */ 1011 private boolean isOffScreen(View descendant) { 1012 return !isWithinDeltaOfScreen(descendant, 0, getHeight()); 1013 } 1014 1015 /** 1016 * @return whether the descendant of this scroll view is within delta 1017 * pixels of being on the screen. 1018 */ 1019 private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) { 1020 descendant.getDrawingRect(mTempRect); 1021 offsetDescendantRectToMyCoords(descendant, mTempRect); 1022 1023 return (mTempRect.bottom + delta) >= getScrollY() 1024 && (mTempRect.top - delta) <= (getScrollY() + height); 1025 } 1026 1027 /** 1028 * Smooth scroll by a Y delta 1029 * 1030 * @param delta the number of pixels to scroll by on the Y axis 1031 */ 1032 private void doScrollY(int delta) { 1033 if (delta != 0) { 1034 if (mSmoothScrollingEnabled) { 1035 smoothScrollBy(0, delta); 1036 } else { 1037 scrollBy(0, delta); 1038 } 1039 } 1040 } 1041 1042 /** 1043 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 1044 * 1045 * @param dx the number of pixels to scroll by on the X axis 1046 * @param dy the number of pixels to scroll by on the Y axis 1047 */ 1048 public final void smoothScrollBy(int dx, int dy) { 1049 if (getChildCount() == 0) { 1050 // Nothing to do. 1051 return; 1052 } 1053 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 1054 if (duration > ANIMATED_SCROLL_GAP) { 1055 final int height = getHeight() - mPaddingBottom - mPaddingTop; 1056 final int bottom = getChildAt(0).getHeight(); 1057 final int maxY = Math.max(0, bottom - height); 1058 final int scrollY = mScrollY; 1059 dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY; 1060 1061 mScroller.startScroll(mScrollX, scrollY, 0, dy); 1062 invalidate(); 1063 } else { 1064 if (!mScroller.isFinished()) { 1065 mScroller.abortAnimation(); 1066 if (mFlingStrictSpan != null) { 1067 mFlingStrictSpan.finish(); 1068 mFlingStrictSpan = null; 1069 } 1070 } 1071 scrollBy(dx, dy); 1072 } 1073 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 1074 } 1075 1076 /** 1077 * Like {@link #scrollTo}, but scroll smoothly instead of immediately. 1078 * 1079 * @param x the position where to scroll on the X axis 1080 * @param y the position where to scroll on the Y axis 1081 */ 1082 public final void smoothScrollTo(int x, int y) { 1083 smoothScrollBy(x - mScrollX, y - mScrollY); 1084 } 1085 1086 /** 1087 * <p>The scroll range of a scroll view is the overall height of all of its 1088 * children.</p> 1089 */ 1090 @Override 1091 protected int computeVerticalScrollRange() { 1092 final int count = getChildCount(); 1093 final int contentHeight = getHeight() - mPaddingBottom - mPaddingTop; 1094 if (count == 0) { 1095 return contentHeight; 1096 } 1097 1098 int scrollRange = getChildAt(0).getBottom(); 1099 final int scrollY = mScrollY; 1100 final int overscrollBottom = Math.max(0, scrollRange - contentHeight); 1101 if (scrollY < 0) { 1102 scrollRange -= scrollY; 1103 } else if (scrollY > overscrollBottom) { 1104 scrollRange += scrollY - overscrollBottom; 1105 } 1106 1107 return scrollRange; 1108 } 1109 1110 @Override 1111 protected int computeVerticalScrollOffset() { 1112 return Math.max(0, super.computeVerticalScrollOffset()); 1113 } 1114 1115 @Override 1116 protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { 1117 ViewGroup.LayoutParams lp = child.getLayoutParams(); 1118 1119 int childWidthMeasureSpec; 1120 int childHeightMeasureSpec; 1121 1122 childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft 1123 + mPaddingRight, lp.width); 1124 1125 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 1126 1127 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1128 } 1129 1130 @Override 1131 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 1132 int parentHeightMeasureSpec, int heightUsed) { 1133 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 1134 1135 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 1136 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 1137 + widthUsed, lp.width); 1138 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( 1139 lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED); 1140 1141 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1142 } 1143 1144 @Override 1145 public void computeScroll() { 1146 if (mScroller.computeScrollOffset()) { 1147 // This is called at drawing time by ViewGroup. We don't want to 1148 // re-show the scrollbars at this point, which scrollTo will do, 1149 // so we replicate most of scrollTo here. 1150 // 1151 // It's a little odd to call onScrollChanged from inside the drawing. 1152 // 1153 // It is, except when you remember that computeScroll() is used to 1154 // animate scrolling. So unless we want to defer the onScrollChanged() 1155 // until the end of the animated scrolling, we don't really have a 1156 // choice here. 1157 // 1158 // I agree. The alternative, which I think would be worse, is to post 1159 // something and tell the subclasses later. This is bad because there 1160 // will be a window where mScrollX/Y is different from what the app 1161 // thinks it is. 1162 // 1163 int oldX = mScrollX; 1164 int oldY = mScrollY; 1165 int x = mScroller.getCurrX(); 1166 int y = mScroller.getCurrY(); 1167 1168 if (oldX != x || oldY != y) { 1169 overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, getScrollRange(), 1170 0, mOverflingDistance, false); 1171 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 1172 1173 final int range = getScrollRange(); 1174 final int overscrollMode = getOverScrollMode(); 1175 if (overscrollMode == OVER_SCROLL_ALWAYS || 1176 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0)) { 1177 if (y < 0 && oldY >= 0) { 1178 mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity()); 1179 } else if (y > range && oldY <= range) { 1180 mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity()); 1181 } 1182 } 1183 } 1184 awakenScrollBars(); 1185 1186 // Keep on drawing until the animation has finished. 1187 postInvalidate(); 1188 } else { 1189 if (mFlingStrictSpan != null) { 1190 mFlingStrictSpan.finish(); 1191 mFlingStrictSpan = null; 1192 } 1193 } 1194 } 1195 1196 /** 1197 * Scrolls the view to the given child. 1198 * 1199 * @param child the View to scroll to 1200 */ 1201 private void scrollToChild(View child) { 1202 child.getDrawingRect(mTempRect); 1203 1204 /* Offset from child's local coordinates to ScrollView coordinates */ 1205 offsetDescendantRectToMyCoords(child, mTempRect); 1206 1207 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1208 1209 if (scrollDelta != 0) { 1210 scrollBy(0, scrollDelta); 1211 } 1212 } 1213 1214 /** 1215 * If rect is off screen, scroll just enough to get it (or at least the 1216 * first screen size chunk of it) on screen. 1217 * 1218 * @param rect The rectangle. 1219 * @param immediate True to scroll immediately without animation 1220 * @return true if scrolling was performed 1221 */ 1222 private boolean scrollToChildRect(Rect rect, boolean immediate) { 1223 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); 1224 final boolean scroll = delta != 0; 1225 if (scroll) { 1226 if (immediate) { 1227 scrollBy(0, delta); 1228 } else { 1229 smoothScrollBy(0, delta); 1230 } 1231 } 1232 return scroll; 1233 } 1234 1235 /** 1236 * Compute the amount to scroll in the Y direction in order to get 1237 * a rectangle completely on the screen (or, if taller than the screen, 1238 * at least the first screen size chunk of it). 1239 * 1240 * @param rect The rect. 1241 * @return The scroll delta. 1242 */ 1243 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { 1244 if (getChildCount() == 0) return 0; 1245 1246 int height = getHeight(); 1247 int screenTop = getScrollY(); 1248 int screenBottom = screenTop + height; 1249 1250 int fadingEdge = getVerticalFadingEdgeLength(); 1251 1252 // leave room for top fading edge as long as rect isn't at very top 1253 if (rect.top > 0) { 1254 screenTop += fadingEdge; 1255 } 1256 1257 // leave room for bottom fading edge as long as rect isn't at very bottom 1258 if (rect.bottom < getChildAt(0).getHeight()) { 1259 screenBottom -= fadingEdge; 1260 } 1261 1262 int scrollYDelta = 0; 1263 1264 if (rect.bottom > screenBottom && rect.top > screenTop) { 1265 // need to move down to get it in view: move down just enough so 1266 // that the entire rectangle is in view (or at least the first 1267 // screen size chunk). 1268 1269 if (rect.height() > height) { 1270 // just enough to get screen size chunk on 1271 scrollYDelta += (rect.top - screenTop); 1272 } else { 1273 // get entire rect at bottom of screen 1274 scrollYDelta += (rect.bottom - screenBottom); 1275 } 1276 1277 // make sure we aren't scrolling beyond the end of our content 1278 int bottom = getChildAt(0).getBottom(); 1279 int distanceToBottom = bottom - screenBottom; 1280 scrollYDelta = Math.min(scrollYDelta, distanceToBottom); 1281 1282 } else if (rect.top < screenTop && rect.bottom < screenBottom) { 1283 // need to move up to get it in view: move up just enough so that 1284 // entire rectangle is in view (or at least the first screen 1285 // size chunk of it). 1286 1287 if (rect.height() > height) { 1288 // screen size chunk 1289 scrollYDelta -= (screenBottom - rect.bottom); 1290 } else { 1291 // entire rect at top 1292 scrollYDelta -= (screenTop - rect.top); 1293 } 1294 1295 // make sure we aren't scrolling any further than the top our content 1296 scrollYDelta = Math.max(scrollYDelta, -getScrollY()); 1297 } 1298 return scrollYDelta; 1299 } 1300 1301 @Override 1302 public void requestChildFocus(View child, View focused) { 1303 if (!mIsLayoutDirty) { 1304 scrollToChild(focused); 1305 } else { 1306 // The child may not be laid out yet, we can't compute the scroll yet 1307 mChildToScrollTo = focused; 1308 } 1309 super.requestChildFocus(child, focused); 1310 } 1311 1312 1313 /** 1314 * When looking for focus in children of a scroll view, need to be a little 1315 * more careful not to give focus to something that is scrolled off screen. 1316 * 1317 * This is more expensive than the default {@link android.view.ViewGroup} 1318 * implementation, otherwise this behavior might have been made the default. 1319 */ 1320 @Override 1321 protected boolean onRequestFocusInDescendants(int direction, 1322 Rect previouslyFocusedRect) { 1323 1324 // convert from forward / backward notation to up / down / left / right 1325 // (ugh). 1326 if (direction == View.FOCUS_FORWARD) { 1327 direction = View.FOCUS_DOWN; 1328 } else if (direction == View.FOCUS_BACKWARD) { 1329 direction = View.FOCUS_UP; 1330 } 1331 1332 final View nextFocus = previouslyFocusedRect == null ? 1333 FocusFinder.getInstance().findNextFocus(this, null, direction) : 1334 FocusFinder.getInstance().findNextFocusFromRect(this, 1335 previouslyFocusedRect, direction); 1336 1337 if (nextFocus == null) { 1338 return false; 1339 } 1340 1341 if (isOffScreen(nextFocus)) { 1342 return false; 1343 } 1344 1345 return nextFocus.requestFocus(direction, previouslyFocusedRect); 1346 } 1347 1348 @Override 1349 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 1350 boolean immediate) { 1351 // offset into coordinate space of this scroll view 1352 rectangle.offset(child.getLeft() - child.getScrollX(), 1353 child.getTop() - child.getScrollY()); 1354 1355 return scrollToChildRect(rectangle, immediate); 1356 } 1357 1358 @Override 1359 public void requestLayout() { 1360 mIsLayoutDirty = true; 1361 super.requestLayout(); 1362 } 1363 1364 @Override 1365 protected void onDetachedFromWindow() { 1366 super.onDetachedFromWindow(); 1367 1368 if (mScrollStrictSpan != null) { 1369 mScrollStrictSpan.finish(); 1370 mScrollStrictSpan = null; 1371 } 1372 if (mFlingStrictSpan != null) { 1373 mFlingStrictSpan.finish(); 1374 mFlingStrictSpan = null; 1375 } 1376 } 1377 1378 @Override 1379 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1380 super.onLayout(changed, l, t, r, b); 1381 mIsLayoutDirty = false; 1382 // Give a child focus if it needs it 1383 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { 1384 scrollToChild(mChildToScrollTo); 1385 } 1386 mChildToScrollTo = null; 1387 1388 // Calling this with the present values causes it to re-clam them 1389 scrollTo(mScrollX, mScrollY); 1390 } 1391 1392 @Override 1393 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1394 super.onSizeChanged(w, h, oldw, oldh); 1395 1396 View currentFocused = findFocus(); 1397 if (null == currentFocused || this == currentFocused) 1398 return; 1399 1400 // If the currently-focused view was visible on the screen when the 1401 // screen was at the old height, then scroll the screen to make that 1402 // view visible with the new screen height. 1403 if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) { 1404 currentFocused.getDrawingRect(mTempRect); 1405 offsetDescendantRectToMyCoords(currentFocused, mTempRect); 1406 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1407 doScrollY(scrollDelta); 1408 } 1409 } 1410 1411 /** 1412 * Return true if child is an descendant of parent, (or equal to the parent). 1413 */ 1414 private boolean isViewDescendantOf(View child, View parent) { 1415 if (child == parent) { 1416 return true; 1417 } 1418 1419 final ViewParent theParent = child.getParent(); 1420 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 1421 } 1422 1423 /** 1424 * Fling the scroll view 1425 * 1426 * @param velocityY The initial velocity in the Y direction. Positive 1427 * numbers mean that the finger/cursor is moving down the screen, 1428 * which means we want to scroll towards the top. 1429 */ 1430 public void fling(int velocityY) { 1431 if (getChildCount() > 0) { 1432 int height = getHeight() - mPaddingBottom - mPaddingTop; 1433 int bottom = getChildAt(0).getHeight(); 1434 1435 mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0, 1436 Math.max(0, bottom - height), 0, height/2); 1437 1438 final boolean movingDown = velocityY > 0; 1439 1440 if (mFlingStrictSpan == null) { 1441 mFlingStrictSpan = StrictMode.enterCriticalSpan("ScrollView-fling"); 1442 } 1443 1444 invalidate(); 1445 } 1446 } 1447 1448 private void endDrag() { 1449 mIsBeingDragged = false; 1450 1451 if (mVelocityTracker != null) { 1452 mVelocityTracker.recycle(); 1453 mVelocityTracker = null; 1454 } 1455 1456 if (mEdgeGlowTop != null) { 1457 mEdgeGlowTop.onRelease(); 1458 mEdgeGlowBottom.onRelease(); 1459 } 1460 1461 if (mScrollStrictSpan != null) { 1462 mScrollStrictSpan.finish(); 1463 mScrollStrictSpan = null; 1464 } 1465 } 1466 1467 /** 1468 * {@inheritDoc} 1469 * 1470 * <p>This version also clamps the scrolling to the bounds of our child. 1471 */ 1472 @Override 1473 public void scrollTo(int x, int y) { 1474 // we rely on the fact the View.scrollBy calls scrollTo. 1475 if (getChildCount() > 0) { 1476 View child = getChildAt(0); 1477 x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); 1478 y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); 1479 if (x != mScrollX || y != mScrollY) { 1480 super.scrollTo(x, y); 1481 } 1482 } 1483 } 1484 1485 @Override 1486 public void setOverScrollMode(int mode) { 1487 if (mode != OVER_SCROLL_NEVER) { 1488 if (mEdgeGlowTop == null) { 1489 Context context = getContext(); 1490 final Resources res = context.getResources(); 1491 final Drawable edge = res.getDrawable(R.drawable.overscroll_edge); 1492 final Drawable glow = res.getDrawable(R.drawable.overscroll_glow); 1493 mEdgeGlowTop = new EdgeGlow(context, edge, glow); 1494 mEdgeGlowBottom = new EdgeGlow(context, edge, glow); 1495 } 1496 } else { 1497 mEdgeGlowTop = null; 1498 mEdgeGlowBottom = null; 1499 } 1500 super.setOverScrollMode(mode); 1501 } 1502 1503 @Override 1504 public void draw(Canvas canvas) { 1505 super.draw(canvas); 1506 if (mEdgeGlowTop != null) { 1507 final int scrollY = mScrollY; 1508 if (!mEdgeGlowTop.isFinished()) { 1509 final int restoreCount = canvas.save(); 1510 final int width = getWidth() - mPaddingLeft - mPaddingRight; 1511 1512 canvas.translate(mPaddingLeft, Math.min(0, scrollY)); 1513 mEdgeGlowTop.setSize(width, getHeight()); 1514 if (mEdgeGlowTop.draw(canvas)) { 1515 invalidate(); 1516 } 1517 canvas.restoreToCount(restoreCount); 1518 } 1519 if (!mEdgeGlowBottom.isFinished()) { 1520 final int restoreCount = canvas.save(); 1521 final int width = getWidth() - mPaddingLeft - mPaddingRight; 1522 final int height = getHeight(); 1523 1524 canvas.translate(-width + mPaddingLeft, 1525 Math.max(getScrollRange(), scrollY) + height); 1526 canvas.rotate(180, width, 0); 1527 mEdgeGlowBottom.setSize(width, height); 1528 if (mEdgeGlowBottom.draw(canvas)) { 1529 invalidate(); 1530 } 1531 canvas.restoreToCount(restoreCount); 1532 } 1533 } 1534 } 1535 1536 private int clamp(int n, int my, int child) { 1537 if (my >= child || n < 0) { 1538 /* my >= child is this case: 1539 * |--------------- me ---------------| 1540 * |------ child ------| 1541 * or 1542 * |--------------- me ---------------| 1543 * |------ child ------| 1544 * or 1545 * |--------------- me ---------------| 1546 * |------ child ------| 1547 * 1548 * n < 0 is this case: 1549 * |------ me ------| 1550 * |-------- child --------| 1551 * |-- mScrollX --| 1552 */ 1553 return 0; 1554 } 1555 if ((my+n) > child) { 1556 /* this case: 1557 * |------ me ------| 1558 * |------ child ------| 1559 * |-- mScrollX --| 1560 */ 1561 return child-my; 1562 } 1563 return n; 1564 } 1565} 1566