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