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