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