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