ScrollView.java revision 17dfce15d5c3e7eae7a3c129019f48e7c5f65063
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.Rect; 24import android.util.AttributeSet; 25import android.view.FocusFinder; 26import android.view.KeyEvent; 27import android.view.MotionEvent; 28import android.view.VelocityTracker; 29import android.view.View; 30import android.view.ViewConfiguration; 31import android.view.ViewGroup; 32import android.view.ViewParent; 33import android.view.animation.AnimationUtils; 34 35import java.util.List; 36 37/** 38 * Layout container for a view hierarchy that can be scrolled by the user, 39 * allowing it to be larger than the physical display. A ScrollView 40 * is a {@link FrameLayout}, meaning you should place one child in it 41 * containing the entire contents to scroll; this child may itself be a layout 42 * manager with a complex hierarchy of objects. A child that is often used 43 * is a {@link LinearLayout} in a vertical orientation, presenting a vertical 44 * array of top-level items that the user can scroll through. 45 * 46 * <p>The {@link TextView} class also 47 * takes care of its own scrolling, so does not require a ScrollView, but 48 * using the two together is possible to achieve the effect of a text view 49 * within a larger container. 50 * 51 * <p>ScrollView only supports vertical scrolling. 52 */ 53public class ScrollView extends FrameLayout { 54 static final int ANIMATED_SCROLL_GAP = 250; 55 56 static final float MAX_SCROLL_FACTOR = 0.5f; 57 58 59 private long mLastScroll; 60 61 private final Rect mTempRect = new Rect(); 62 private OverScroller mScroller; 63 64 /** 65 * Flag to indicate that we are moving focus ourselves. This is so the 66 * code that watches for focus changes initiated outside this ScrollView 67 * knows that it does not have to do anything. 68 */ 69 private boolean mScrollViewMovedFocus; 70 71 /** 72 * Position of the last motion event. 73 */ 74 private float mLastMotionY; 75 76 /** 77 * True when the layout has changed but the traversal has not come through yet. 78 * Ideally the view hierarchy would keep track of this for us. 79 */ 80 private boolean mIsLayoutDirty = true; 81 82 /** 83 * The child to give focus to in the event that a child has requested focus while the 84 * layout is dirty. This prevents the scroll from being wrong if the child has not been 85 * laid out before requesting focus. 86 */ 87 private View mChildToScrollTo = null; 88 89 /** 90 * True if the user is currently dragging this ScrollView around. This is 91 * not the same as 'is being flinged', which can be checked by 92 * mScroller.isFinished() (flinging begins when the user lifts his finger). 93 */ 94 private boolean mIsBeingDragged = false; 95 96 /** 97 * Determines speed during touch scrolling 98 */ 99 private VelocityTracker mVelocityTracker; 100 101 /** 102 * When set to true, the scroll view measure its child to make it fill the currently 103 * visible area. 104 */ 105 private boolean mFillViewport; 106 107 /** 108 * Whether arrow scrolling is animated. 109 */ 110 private boolean mSmoothScrollingEnabled = true; 111 112 private int mTouchSlop; 113 private int mMinimumVelocity; 114 private int mMaximumVelocity; 115 116 public ScrollView(Context context) { 117 this(context, null); 118 } 119 120 public ScrollView(Context context, AttributeSet attrs) { 121 this(context, attrs, com.android.internal.R.attr.scrollViewStyle); 122 } 123 124 public ScrollView(Context context, AttributeSet attrs, int defStyle) { 125 super(context, attrs, defStyle); 126 initScrollView(); 127 128 TypedArray a = 129 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ScrollView, defStyle, 0); 130 131 setFillViewport(a.getBoolean(R.styleable.ScrollView_fillViewport, false)); 132 133 a.recycle(); 134 } 135 136 @Override 137 protected float getTopFadingEdgeStrength() { 138 if (getChildCount() == 0) { 139 return 0.0f; 140 } 141 142 final int length = getVerticalFadingEdgeLength(); 143 if (mScrollY < length) { 144 return mScrollY / (float) length; 145 } 146 147 return 1.0f; 148 } 149 150 @Override 151 protected float getBottomFadingEdgeStrength() { 152 if (getChildCount() == 0) { 153 return 0.0f; 154 } 155 156 final int length = getVerticalFadingEdgeLength(); 157 final int bottomEdge = getHeight() - mPaddingBottom; 158 final int span = getChildAt(0).getBottom() - mScrollY - bottomEdge; 159 if (span < length) { 160 return span / (float) length; 161 } 162 163 return 1.0f; 164 } 165 166 /** 167 * @return The maximum amount this scroll view will scroll in response to 168 * an arrow event. 169 */ 170 public int getMaxScrollAmount() { 171 return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop)); 172 } 173 174 175 private void initScrollView() { 176 mScroller = new OverScroller(getContext()); 177 setFocusable(true); 178 setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); 179 setWillNotDraw(false); 180 final ViewConfiguration configuration = ViewConfiguration.get(mContext); 181 mTouchSlop = configuration.getScaledTouchSlop(); 182 mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); 183 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 184 } 185 186 @Override 187 public void addView(View child) { 188 if (getChildCount() > 0) { 189 throw new IllegalStateException("ScrollView can host only one direct child"); 190 } 191 192 super.addView(child); 193 } 194 195 @Override 196 public void addView(View child, int index) { 197 if (getChildCount() > 0) { 198 throw new IllegalStateException("ScrollView can host only one direct child"); 199 } 200 201 super.addView(child, index); 202 } 203 204 @Override 205 public void addView(View child, ViewGroup.LayoutParams params) { 206 if (getChildCount() > 0) { 207 throw new IllegalStateException("ScrollView can host only one direct child"); 208 } 209 210 super.addView(child, params); 211 } 212 213 @Override 214 public void addView(View child, int index, ViewGroup.LayoutParams params) { 215 if (getChildCount() > 0) { 216 throw new IllegalStateException("ScrollView can host only one direct child"); 217 } 218 219 super.addView(child, index, params); 220 } 221 222 /** 223 * @return Returns true this ScrollView can be scrolled 224 */ 225 private boolean canScroll() { 226 View child = getChildAt(0); 227 if (child != null) { 228 int childHeight = child.getHeight(); 229 return getHeight() < childHeight + mPaddingTop + mPaddingBottom; 230 } 231 return false; 232 } 233 234 /** 235 * Indicates whether this ScrollView's content is stretched to fill the viewport. 236 * 237 * @return True if the content fills the viewport, false otherwise. 238 */ 239 public boolean isFillViewport() { 240 return mFillViewport; 241 } 242 243 /** 244 * Indicates this ScrollView whether it should stretch its content height to fill 245 * the viewport or not. 246 * 247 * @param fillViewport True to stretch the content's height to the viewport's 248 * boundaries, false otherwise. 249 */ 250 public void setFillViewport(boolean fillViewport) { 251 if (fillViewport != mFillViewport) { 252 mFillViewport = fillViewport; 253 requestLayout(); 254 } 255 } 256 257 /** 258 * @return Whether arrow scrolling will animate its transition. 259 */ 260 public boolean isSmoothScrollingEnabled() { 261 return mSmoothScrollingEnabled; 262 } 263 264 /** 265 * Set whether arrow scrolling will animate its transition. 266 * @param smoothScrollingEnabled whether arrow scrolling will animate its transition 267 */ 268 public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) { 269 mSmoothScrollingEnabled = smoothScrollingEnabled; 270 } 271 272 @Override 273 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 274 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 275 276 if (!mFillViewport) { 277 return; 278 } 279 280 final int heightMode = MeasureSpec.getMode(heightMeasureSpec); 281 if (heightMode == MeasureSpec.UNSPECIFIED) { 282 return; 283 } 284 285 if (getChildCount() > 0) { 286 final View child = getChildAt(0); 287 int height = getMeasuredHeight(); 288 if (child.getMeasuredHeight() < height) { 289 final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); 290 291 int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, mPaddingLeft 292 + mPaddingRight, lp.width); 293 height -= mPaddingTop; 294 height -= mPaddingBottom; 295 int childHeightMeasureSpec = 296 MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 297 298 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 299 } 300 } 301 } 302 303 @Override 304 public boolean dispatchKeyEvent(KeyEvent event) { 305 // Let the focused view and/or our descendants get the key first 306 boolean handled = super.dispatchKeyEvent(event); 307 if (handled) { 308 return true; 309 } 310 return executeKeyEvent(event); 311 } 312 313 /** 314 * You can call this function yourself to have the scroll view perform 315 * scrolling from a key event, just as if the event had been dispatched to 316 * it by the view hierarchy. 317 * 318 * @param event The key event to execute. 319 * @return Return true if the event was handled, else false. 320 */ 321 public boolean executeKeyEvent(KeyEvent event) { 322 mTempRect.setEmpty(); 323 324 if (!canScroll()) { 325 if (isFocused()) { 326 View currentFocused = findFocus(); 327 if (currentFocused == this) currentFocused = null; 328 View nextFocused = FocusFinder.getInstance().findNextFocus(this, 329 currentFocused, View.FOCUS_DOWN); 330 return nextFocused != null 331 && nextFocused != this 332 && nextFocused.requestFocus(View.FOCUS_DOWN); 333 } 334 return false; 335 } 336 337 boolean handled = false; 338 if (event.getAction() == KeyEvent.ACTION_DOWN) { 339 switch (event.getKeyCode()) { 340 case KeyEvent.KEYCODE_DPAD_UP: 341 if (!event.isAltPressed()) { 342 handled = arrowScroll(View.FOCUS_UP); 343 } else { 344 handled = fullScroll(View.FOCUS_UP); 345 } 346 break; 347 case KeyEvent.KEYCODE_DPAD_DOWN: 348 if (!event.isAltPressed()) { 349 handled = arrowScroll(View.FOCUS_DOWN); 350 } else { 351 handled = fullScroll(View.FOCUS_DOWN); 352 } 353 break; 354 case KeyEvent.KEYCODE_SPACE: 355 pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN); 356 break; 357 } 358 } 359 360 return handled; 361 } 362 363 @Override 364 public boolean onInterceptTouchEvent(MotionEvent ev) { 365 /* 366 * This method JUST determines whether we want to intercept the motion. 367 * If we return true, onMotionEvent will be called and we do the actual 368 * scrolling there. 369 */ 370 371 /* 372 * Shortcut the most recurring case: the user is in the dragging 373 * state and he is moving his finger. We want to intercept this 374 * motion. 375 */ 376 final int action = ev.getAction(); 377 if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { 378 return true; 379 } 380 381 final float y = ev.getY(); 382 383 switch (action) { 384 case MotionEvent.ACTION_MOVE: 385 /* 386 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 387 * whether the user has moved far enough from his original down touch. 388 */ 389 390 /* 391 * Locally do absolute value. mLastMotionY is set to the y value 392 * of the down event. 393 */ 394 final int yDiff = (int) Math.abs(y - mLastMotionY); 395 if (yDiff > mTouchSlop) { 396 mIsBeingDragged = true; 397 mLastMotionY = y; 398 } 399 break; 400 401 case MotionEvent.ACTION_DOWN: 402 /* Remember location of down touch */ 403 mLastMotionY = y; 404 405 /* 406 * If being flinged and user touches the screen, initiate drag; 407 * otherwise don't. mScroller.isFinished should be false when 408 * being flinged. 409 */ 410 mIsBeingDragged = !mScroller.isFinished(); 411 break; 412 413 case MotionEvent.ACTION_CANCEL: 414 case MotionEvent.ACTION_UP: 415 /* Release the drag */ 416 mIsBeingDragged = false; 417 break; 418 } 419 420 /* 421 * The only time we want to intercept motion events is if we are in the 422 * drag mode. 423 */ 424 return mIsBeingDragged; 425 } 426 427 @Override 428 public boolean onTouchEvent(MotionEvent ev) { 429 430 if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { 431 // Don't handle edge touches immediately -- they may actually belong to one of our 432 // descendants. 433 return false; 434 } 435 436 if (mVelocityTracker == null) { 437 mVelocityTracker = VelocityTracker.obtain(); 438 } 439 mVelocityTracker.addMovement(ev); 440 441 final int action = ev.getAction(); 442 final float y = ev.getY(); 443 444 switch (action) { 445 case MotionEvent.ACTION_DOWN: 446 /* 447 * If being flinged and user touches, stop the fling. isFinished 448 * will be false if being flinged. 449 */ 450 if (!mScroller.isFinished()) { 451 mScroller.abortAnimation(); 452 } 453 454 // Remember where the motion event started 455 mLastMotionY = y; 456 break; 457 case MotionEvent.ACTION_MOVE: 458 // Scroll to follow the motion event 459 final int deltaY = (int) (mLastMotionY - y); 460 mLastMotionY = y; 461 462 super.scrollTo(mScrollX, mScrollY + deltaY); 463 break; 464 case MotionEvent.ACTION_UP: 465 final VelocityTracker velocityTracker = mVelocityTracker; 466 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 467 int initialVelocity = (int) velocityTracker.getYVelocity(); 468 469 if (getChildCount() > 0) { 470 if ((Math.abs(initialVelocity) > mMinimumVelocity)) { 471 fling(-initialVelocity); 472 } else { 473 final int bottom = Math.max(0, getChildAt(0).getHeight() - 474 (getHeight() - mPaddingBottom - mPaddingTop)); 475 if (mScroller.springback(mScrollX, mScrollY, 0, 0, 0, bottom)) { 476 invalidate(); 477 } 478 } 479 } 480 481 if (mVelocityTracker != null) { 482 mVelocityTracker.recycle(); 483 mVelocityTracker = null; 484 } 485 } 486 return true; 487 } 488 489 /** 490 * <p> 491 * Finds the next focusable component that fits in this View's bounds 492 * (excluding fading edges) pretending that this View's top is located at 493 * the parameter top. 494 * </p> 495 * 496 * @param topFocus look for a candidate is the one at the top of the bounds 497 * if topFocus is true, or at the bottom of the bounds if topFocus is 498 * false 499 * @param top the top offset of the bounds in which a focusable must be 500 * found (the fading edge is assumed to start at this position) 501 * @param preferredFocusable the View that has highest priority and will be 502 * returned if it is within my bounds (null is valid) 503 * @return the next focusable component in the bounds or null if none can be 504 * found 505 */ 506 private View findFocusableViewInMyBounds(final boolean topFocus, 507 final int top, View preferredFocusable) { 508 /* 509 * The fading edge's transparent side should be considered for focus 510 * since it's mostly visible, so we divide the actual fading edge length 511 * by 2. 512 */ 513 final int fadingEdgeLength = getVerticalFadingEdgeLength() / 2; 514 final int topWithoutFadingEdge = top + fadingEdgeLength; 515 final int bottomWithoutFadingEdge = top + getHeight() - fadingEdgeLength; 516 517 if ((preferredFocusable != null) 518 && (preferredFocusable.getTop() < bottomWithoutFadingEdge) 519 && (preferredFocusable.getBottom() > topWithoutFadingEdge)) { 520 return preferredFocusable; 521 } 522 523 return findFocusableViewInBounds(topFocus, topWithoutFadingEdge, 524 bottomWithoutFadingEdge); 525 } 526 527 /** 528 * <p> 529 * Finds the next focusable component that fits in the specified bounds. 530 * </p> 531 * 532 * @param topFocus look for a candidate is the one at the top of the bounds 533 * if topFocus is true, or at the bottom of the bounds if topFocus is 534 * false 535 * @param top the top offset of the bounds in which a focusable must be 536 * found 537 * @param bottom the bottom offset of the bounds in which a focusable must 538 * be found 539 * @return the next focusable component in the bounds or null if none can 540 * be found 541 */ 542 private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) { 543 544 List<View> focusables = getFocusables(View.FOCUS_FORWARD); 545 View focusCandidate = null; 546 547 /* 548 * A fully contained focusable is one where its top is below the bound's 549 * top, and its bottom is above the bound's bottom. A partially 550 * contained focusable is one where some part of it is within the 551 * bounds, but it also has some part that is not within bounds. A fully contained 552 * focusable is preferred to a partially contained focusable. 553 */ 554 boolean foundFullyContainedFocusable = false; 555 556 int count = focusables.size(); 557 for (int i = 0; i < count; i++) { 558 View view = focusables.get(i); 559 int viewTop = view.getTop(); 560 int viewBottom = view.getBottom(); 561 562 if (top < viewBottom && viewTop < bottom) { 563 /* 564 * the focusable is in the target area, it is a candidate for 565 * focusing 566 */ 567 568 final boolean viewIsFullyContained = (top < viewTop) && 569 (viewBottom < bottom); 570 571 if (focusCandidate == null) { 572 /* No candidate, take this one */ 573 focusCandidate = view; 574 foundFullyContainedFocusable = viewIsFullyContained; 575 } else { 576 final boolean viewIsCloserToBoundary = 577 (topFocus && viewTop < focusCandidate.getTop()) || 578 (!topFocus && viewBottom > focusCandidate 579 .getBottom()); 580 581 if (foundFullyContainedFocusable) { 582 if (viewIsFullyContained && viewIsCloserToBoundary) { 583 /* 584 * We're dealing with only fully contained views, so 585 * it has to be closer to the boundary to beat our 586 * candidate 587 */ 588 focusCandidate = view; 589 } 590 } else { 591 if (viewIsFullyContained) { 592 /* Any fully contained view beats a partially contained view */ 593 focusCandidate = view; 594 foundFullyContainedFocusable = true; 595 } else if (viewIsCloserToBoundary) { 596 /* 597 * Partially contained view beats another partially 598 * contained view if it's closer 599 */ 600 focusCandidate = view; 601 } 602 } 603 } 604 } 605 } 606 607 return focusCandidate; 608 } 609 610 /** 611 * <p>Handles scrolling in response to a "page up/down" shortcut press. This 612 * method will scroll the view by one page up or down and give the focus 613 * to the topmost/bottommost component in the new visible area. If no 614 * component is a good candidate for focus, this scrollview reclaims the 615 * focus.</p> 616 * 617 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 618 * to go one page up or 619 * {@link android.view.View#FOCUS_DOWN} to go one page down 620 * @return true if the key event is consumed by this method, false otherwise 621 */ 622 public boolean pageScroll(int direction) { 623 boolean down = direction == View.FOCUS_DOWN; 624 int height = getHeight(); 625 626 if (down) { 627 mTempRect.top = getScrollY() + height; 628 int count = getChildCount(); 629 if (count > 0) { 630 View view = getChildAt(count - 1); 631 if (mTempRect.top + height > view.getBottom()) { 632 mTempRect.top = view.getBottom() - height; 633 } 634 } 635 } else { 636 mTempRect.top = getScrollY() - height; 637 if (mTempRect.top < 0) { 638 mTempRect.top = 0; 639 } 640 } 641 mTempRect.bottom = mTempRect.top + height; 642 643 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 644 } 645 646 /** 647 * <p>Handles scrolling in response to a "home/end" shortcut press. This 648 * method will scroll the view to the top or bottom and give the focus 649 * to the topmost/bottommost component in the new visible area. If no 650 * component is a good candidate for focus, this scrollview reclaims the 651 * focus.</p> 652 * 653 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 654 * to go the top of the view or 655 * {@link android.view.View#FOCUS_DOWN} to go the bottom 656 * @return true if the key event is consumed by this method, false otherwise 657 */ 658 public boolean fullScroll(int direction) { 659 boolean down = direction == View.FOCUS_DOWN; 660 int height = getHeight(); 661 662 mTempRect.top = 0; 663 mTempRect.bottom = height; 664 665 if (down) { 666 int count = getChildCount(); 667 if (count > 0) { 668 View view = getChildAt(count - 1); 669 mTempRect.bottom = view.getBottom(); 670 mTempRect.top = mTempRect.bottom - height; 671 } 672 } 673 674 return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); 675 } 676 677 /** 678 * <p>Scrolls the view to make the area defined by <code>top</code> and 679 * <code>bottom</code> visible. This method attempts to give the focus 680 * to a component visible in this area. If no component can be focused in 681 * the new visible area, the focus is reclaimed by this scrollview.</p> 682 * 683 * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} 684 * to go upward 685 * {@link android.view.View#FOCUS_DOWN} to downward 686 * @param top the top offset of the new area to be made visible 687 * @param bottom the bottom offset of the new area to be made visible 688 * @return true if the key event is consumed by this method, false otherwise 689 */ 690 private boolean scrollAndFocus(int direction, int top, int bottom) { 691 boolean handled = true; 692 693 int height = getHeight(); 694 int containerTop = getScrollY(); 695 int containerBottom = containerTop + height; 696 boolean up = direction == View.FOCUS_UP; 697 698 View newFocused = findFocusableViewInBounds(up, top, bottom); 699 if (newFocused == null) { 700 newFocused = this; 701 } 702 703 if (top >= containerTop && bottom <= containerBottom) { 704 handled = false; 705 } else { 706 int delta = up ? (top - containerTop) : (bottom - containerBottom); 707 doScrollY(delta); 708 } 709 710 if (newFocused != findFocus() && newFocused.requestFocus(direction)) { 711 mScrollViewMovedFocus = true; 712 mScrollViewMovedFocus = false; 713 } 714 715 return handled; 716 } 717 718 /** 719 * Handle scrolling in response to an up or down arrow click. 720 * 721 * @param direction The direction corresponding to the arrow key that was 722 * pressed 723 * @return True if we consumed the event, false otherwise 724 */ 725 public boolean arrowScroll(int direction) { 726 727 View currentFocused = findFocus(); 728 if (currentFocused == this) currentFocused = null; 729 730 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); 731 732 final int maxJump = getMaxScrollAmount(); 733 734 if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) { 735 nextFocused.getDrawingRect(mTempRect); 736 offsetDescendantRectToMyCoords(nextFocused, mTempRect); 737 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 738 doScrollY(scrollDelta); 739 nextFocused.requestFocus(direction); 740 } else { 741 // no new focus 742 int scrollDelta = maxJump; 743 744 if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { 745 scrollDelta = getScrollY(); 746 } else if (direction == View.FOCUS_DOWN) { 747 if (getChildCount() > 0) { 748 int daBottom = getChildAt(0).getBottom(); 749 750 int screenBottom = getScrollY() + getHeight(); 751 752 if (daBottom - screenBottom < maxJump) { 753 scrollDelta = daBottom - screenBottom; 754 } 755 } 756 } 757 if (scrollDelta == 0) { 758 return false; 759 } 760 doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); 761 } 762 763 if (currentFocused != null && currentFocused.isFocused() 764 && isOffScreen(currentFocused)) { 765 // previously focused item still has focus and is off screen, give 766 // it up (take it back to ourselves) 767 // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are 768 // sure to 769 // get it) 770 final int descendantFocusability = getDescendantFocusability(); // save 771 setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); 772 requestFocus(); 773 setDescendantFocusability(descendantFocusability); // restore 774 } 775 return true; 776 } 777 778 /** 779 * @return whether the descendant of this scroll view is scrolled off 780 * screen. 781 */ 782 private boolean isOffScreen(View descendant) { 783 return !isWithinDeltaOfScreen(descendant, 0, getHeight()); 784 } 785 786 /** 787 * @return whether the descendant of this scroll view is within delta 788 * pixels of being on the screen. 789 */ 790 private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) { 791 descendant.getDrawingRect(mTempRect); 792 offsetDescendantRectToMyCoords(descendant, mTempRect); 793 794 return (mTempRect.bottom + delta) >= getScrollY() 795 && (mTempRect.top - delta) <= (getScrollY() + height); 796 } 797 798 /** 799 * Smooth scroll by a Y delta 800 * 801 * @param delta the number of pixels to scroll by on the Y axis 802 */ 803 private void doScrollY(int delta) { 804 if (delta != 0) { 805 if (mSmoothScrollingEnabled) { 806 smoothScrollBy(0, delta); 807 } else { 808 scrollBy(0, delta); 809 } 810 } 811 } 812 813 /** 814 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 815 * 816 * @param dx the number of pixels to scroll by on the X axis 817 * @param dy the number of pixels to scroll by on the Y axis 818 */ 819 public final void smoothScrollBy(int dx, int dy) { 820 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 821 if (duration > ANIMATED_SCROLL_GAP) { 822 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 823 awakenScrollBars(mScroller.getDuration()); 824 invalidate(); 825 } else { 826 if (!mScroller.isFinished()) { 827 mScroller.abortAnimation(); 828 } 829 scrollBy(dx, dy); 830 } 831 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 832 } 833 834 /** 835 * Like {@link #scrollTo}, but scroll smoothly instead of immediately. 836 * 837 * @param x the position where to scroll on the X axis 838 * @param y the position where to scroll on the Y axis 839 */ 840 public final void smoothScrollTo(int x, int y) { 841 smoothScrollBy(x - mScrollX, y - mScrollY); 842 } 843 844 /** 845 * <p>The scroll range of a scroll view is the overall height of all of its 846 * children.</p> 847 */ 848 @Override 849 protected int computeVerticalScrollRange() { 850 int count = getChildCount(); 851 return count == 0 ? getHeight() : (getChildAt(0)).getBottom(); 852 } 853 854 855 @Override 856 protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { 857 ViewGroup.LayoutParams lp = child.getLayoutParams(); 858 859 int childWidthMeasureSpec; 860 int childHeightMeasureSpec; 861 862 childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft 863 + mPaddingRight, lp.width); 864 865 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 866 867 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 868 } 869 870 @Override 871 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 872 int parentHeightMeasureSpec, int heightUsed) { 873 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 874 875 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 876 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 877 + widthUsed, lp.width); 878 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( 879 lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED); 880 881 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 882 } 883 884 @Override 885 public void computeScroll() { 886 if (mScroller.computeScrollOffset()) { 887 // This is called at drawing time by ViewGroup. We don't want to 888 // re-show the scrollbars at this point, which scrollTo will do, 889 // so we replicate most of scrollTo here. 890 // 891 // It's a little odd to call onScrollChanged from inside the drawing. 892 // 893 // It is, except when you remember that computeScroll() is used to 894 // animate scrolling. So unless we want to defer the onScrollChanged() 895 // until the end of the animated scrolling, we don't really have a 896 // choice here. 897 // 898 // I agree. The alternative, which I think would be worse, is to post 899 // something and tell the subclasses later. This is bad because there 900 // will be a window where mScrollX/Y is different from what the app 901 // thinks it is. 902 // 903 int oldX = mScrollX; 904 int oldY = mScrollY; 905 int x = mScroller.getCurrX(); 906 int y = mScroller.getCurrY(); 907 908 mScrollX = x; 909 mScrollY = y; 910 911 if (oldX != mScrollX || oldY != mScrollY) { 912 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 913 } 914 915 // Keep on drawing until the animation has finished. 916 postInvalidate(); 917 } 918 } 919 920 /** 921 * Scrolls the view to the given child. 922 * 923 * @param child the View to scroll to 924 */ 925 private void scrollToChild(View child) { 926 child.getDrawingRect(mTempRect); 927 928 /* Offset from child's local coordinates to ScrollView coordinates */ 929 offsetDescendantRectToMyCoords(child, mTempRect); 930 931 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 932 933 if (scrollDelta != 0) { 934 scrollBy(0, scrollDelta); 935 } 936 } 937 938 /** 939 * If rect is off screen, scroll just enough to get it (or at least the 940 * first screen size chunk of it) on screen. 941 * 942 * @param rect The rectangle. 943 * @param immediate True to scroll immediately without animation 944 * @return true if scrolling was performed 945 */ 946 private boolean scrollToChildRect(Rect rect, boolean immediate) { 947 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); 948 final boolean scroll = delta != 0; 949 if (scroll) { 950 if (immediate) { 951 scrollBy(0, delta); 952 } else { 953 smoothScrollBy(0, delta); 954 } 955 } 956 return scroll; 957 } 958 959 /** 960 * Compute the amount to scroll in the Y direction in order to get 961 * a rectangle completely on the screen (or, if taller than the screen, 962 * at least the first screen size chunk of it). 963 * 964 * @param rect The rect. 965 * @return The scroll delta. 966 */ 967 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { 968 if (getChildCount() == 0) return 0; 969 970 int height = getHeight(); 971 int screenTop = getScrollY(); 972 int screenBottom = screenTop + height; 973 974 int fadingEdge = getVerticalFadingEdgeLength(); 975 976 // leave room for top fading edge as long as rect isn't at very top 977 if (rect.top > 0) { 978 screenTop += fadingEdge; 979 } 980 981 // leave room for bottom fading edge as long as rect isn't at very bottom 982 if (rect.bottom < getChildAt(0).getHeight()) { 983 screenBottom -= fadingEdge; 984 } 985 986 int scrollYDelta = 0; 987 988 if (rect.bottom > screenBottom && rect.top > screenTop) { 989 // need to move down to get it in view: move down just enough so 990 // that the entire rectangle is in view (or at least the first 991 // screen size chunk). 992 993 if (rect.height() > height) { 994 // just enough to get screen size chunk on 995 scrollYDelta += (rect.top - screenTop); 996 } else { 997 // get entire rect at bottom of screen 998 scrollYDelta += (rect.bottom - screenBottom); 999 } 1000 1001 // make sure we aren't scrolling beyond the end of our content 1002 int bottom = getChildAt(0).getBottom(); 1003 int distanceToBottom = bottom - screenBottom; 1004 scrollYDelta = Math.min(scrollYDelta, distanceToBottom); 1005 1006 } else if (rect.top < screenTop && rect.bottom < screenBottom) { 1007 // need to move up to get it in view: move up just enough so that 1008 // entire rectangle is in view (or at least the first screen 1009 // size chunk of it). 1010 1011 if (rect.height() > height) { 1012 // screen size chunk 1013 scrollYDelta -= (screenBottom - rect.bottom); 1014 } else { 1015 // entire rect at top 1016 scrollYDelta -= (screenTop - rect.top); 1017 } 1018 1019 // make sure we aren't scrolling any further than the top our content 1020 scrollYDelta = Math.max(scrollYDelta, -getScrollY()); 1021 } 1022 return scrollYDelta; 1023 } 1024 1025 @Override 1026 public void requestChildFocus(View child, View focused) { 1027 if (!mScrollViewMovedFocus) { 1028 if (!mIsLayoutDirty) { 1029 scrollToChild(focused); 1030 } else { 1031 // The child may not be laid out yet, we can't compute the scroll yet 1032 mChildToScrollTo = focused; 1033 } 1034 } 1035 super.requestChildFocus(child, focused); 1036 } 1037 1038 1039 /** 1040 * When looking for focus in children of a scroll view, need to be a little 1041 * more careful not to give focus to something that is scrolled off screen. 1042 * 1043 * This is more expensive than the default {@link android.view.ViewGroup} 1044 * implementation, otherwise this behavior might have been made the default. 1045 */ 1046 @Override 1047 protected boolean onRequestFocusInDescendants(int direction, 1048 Rect previouslyFocusedRect) { 1049 1050 // convert from forward / backward notation to up / down / left / right 1051 // (ugh). 1052 if (direction == View.FOCUS_FORWARD) { 1053 direction = View.FOCUS_DOWN; 1054 } else if (direction == View.FOCUS_BACKWARD) { 1055 direction = View.FOCUS_UP; 1056 } 1057 1058 final View nextFocus = previouslyFocusedRect == null ? 1059 FocusFinder.getInstance().findNextFocus(this, null, direction) : 1060 FocusFinder.getInstance().findNextFocusFromRect(this, 1061 previouslyFocusedRect, direction); 1062 1063 if (nextFocus == null) { 1064 return false; 1065 } 1066 1067 if (isOffScreen(nextFocus)) { 1068 return false; 1069 } 1070 1071 return nextFocus.requestFocus(direction, previouslyFocusedRect); 1072 } 1073 1074 @Override 1075 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 1076 boolean immediate) { 1077 // offset into coordinate space of this scroll view 1078 rectangle.offset(child.getLeft() - child.getScrollX(), 1079 child.getTop() - child.getScrollY()); 1080 1081 return scrollToChildRect(rectangle, immediate); 1082 } 1083 1084 @Override 1085 public void requestLayout() { 1086 mIsLayoutDirty = true; 1087 super.requestLayout(); 1088 } 1089 1090 @Override 1091 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1092 super.onLayout(changed, l, t, r, b); 1093 mIsLayoutDirty = false; 1094 // Give a child focus if it needs it 1095 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { 1096 scrollToChild(mChildToScrollTo); 1097 } 1098 mChildToScrollTo = null; 1099 1100 // Calling this with the present values causes it to re-clam them 1101 scrollTo(mScrollX, mScrollY); 1102 } 1103 1104 @Override 1105 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1106 super.onSizeChanged(w, h, oldw, oldh); 1107 1108 View currentFocused = findFocus(); 1109 if (null == currentFocused || this == currentFocused) 1110 return; 1111 1112 // If the currently-focused view was visible on the screen when the 1113 // screen was at the old height, then scroll the screen to make that 1114 // view visible with the new screen height. 1115 if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) { 1116 currentFocused.getDrawingRect(mTempRect); 1117 offsetDescendantRectToMyCoords(currentFocused, mTempRect); 1118 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1119 doScrollY(scrollDelta); 1120 } 1121 } 1122 1123 /** 1124 * Return true if child is an descendant of parent, (or equal to the parent). 1125 */ 1126 private boolean isViewDescendantOf(View child, View parent) { 1127 if (child == parent) { 1128 return true; 1129 } 1130 1131 final ViewParent theParent = child.getParent(); 1132 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 1133 } 1134 1135 /** 1136 * Fling the scroll view 1137 * 1138 * @param velocityY The initial velocity in the Y direction. Positive 1139 * numbers mean that the finger/curor is moving down the screen, 1140 * which means we want to scroll towards the top. 1141 */ 1142 public void fling(int velocityY) { 1143 if (getChildCount() > 0) { 1144 int height = getHeight() - mPaddingBottom - mPaddingTop; 1145 int bottom = getChildAt(0).getHeight(); 1146 1147 mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0, 1148 Math.max(0, bottom - height), 0, height/2); 1149 1150 final boolean movingDown = velocityY > 0; 1151 1152 View newFocused = 1153 findFocusableViewInMyBounds(movingDown, mScroller.getFinalY(), findFocus()); 1154 if (newFocused == null) { 1155 newFocused = this; 1156 } 1157 1158 if (newFocused != findFocus() 1159 && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) { 1160 mScrollViewMovedFocus = true; 1161 mScrollViewMovedFocus = false; 1162 } 1163 1164 awakenScrollBars(mScroller.getDuration()); 1165 invalidate(); 1166 } 1167 } 1168 1169 /** 1170 * {@inheritDoc} 1171 * 1172 * <p>This version also clamps the scrolling to the bounds of our child. 1173 */ 1174 public void scrollTo(int x, int y) { 1175 // we rely on the fact the View.scrollBy calls scrollTo. 1176 if (getChildCount() > 0) { 1177 View child = getChildAt(0); 1178 x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); 1179 y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); 1180 if (x != mScrollX || y != mScrollY) { 1181 super.scrollTo(x, y); 1182 } 1183 } 1184 } 1185 1186 private int clamp(int n, int my, int child) { 1187 if (my >= child || n < 0) { 1188 /* my >= child is this case: 1189 * |--------------- me ---------------| 1190 * |------ child ------| 1191 * or 1192 * |--------------- me ---------------| 1193 * |------ child ------| 1194 * or 1195 * |--------------- me ---------------| 1196 * |------ child ------| 1197 * 1198 * n < 0 is this case: 1199 * |------ me ------| 1200 * |-------- child --------| 1201 * |-- mScrollX --| 1202 */ 1203 return 0; 1204 } 1205 if ((my+n) > child) { 1206 /* this case: 1207 * |------ me ------| 1208 * |------ child ------| 1209 * |-- mScrollX --| 1210 */ 1211 return child-my; 1212 } 1213 return n; 1214 } 1215} 1216