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