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