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