HorizontalScrollView.java revision f6a6c97062d905be267fcb8f70e6eb06fb7e5ab4
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 float 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 float x = 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 float x = 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 invalidate(); 509 } 510 break; 511 case MotionEvent.ACTION_POINTER_DOWN: { 512 final int index = ev.getActionIndex(); 513 mLastMotionX = ev.getX(index); 514 mActivePointerId = ev.getPointerId(index); 515 break; 516 } 517 case MotionEvent.ACTION_POINTER_UP: 518 onSecondaryPointerUp(ev); 519 mLastMotionX = 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 mIsBeingDragged = getChildCount() != 0; 540 if (!mIsBeingDragged) { 541 return false; 542 } 543 544 /* 545 * If being flinged and user touches, stop the fling. isFinished 546 * will be false if being flinged. 547 */ 548 if (!mScroller.isFinished()) { 549 mScroller.abortAnimation(); 550 } 551 552 // Remember where the motion event started 553 mLastMotionX = ev.getX(); 554 mActivePointerId = ev.getPointerId(0); 555 break; 556 } 557 case MotionEvent.ACTION_MOVE: 558 if (mIsBeingDragged) { 559 // Scroll to follow the motion event 560 final int activePointerIndex = ev.findPointerIndex(mActivePointerId); 561 final float x = ev.getX(activePointerIndex); 562 final int deltaX = (int) (mLastMotionX - x); 563 mLastMotionX = x; 564 565 final int oldX = mScrollX; 566 final int oldY = mScrollY; 567 final int range = getScrollRange(); 568 final int overscrollMode = getOverScrollMode(); 569 final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS || 570 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); 571 572 if (overScrollBy(deltaX, 0, mScrollX, 0, range, 0, 573 mOverscrollDistance, 0, true)) { 574 // Break our velocity if we hit a scroll barrier. 575 mVelocityTracker.clear(); 576 } 577 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 578 579 if (canOverscroll) { 580 final int pulledToX = oldX + deltaX; 581 if (pulledToX < 0) { 582 mEdgeGlowLeft.onPull((float) deltaX / getWidth()); 583 if (!mEdgeGlowRight.isFinished()) { 584 mEdgeGlowRight.onRelease(); 585 } 586 } else if (pulledToX > range) { 587 mEdgeGlowRight.onPull((float) deltaX / getWidth()); 588 if (!mEdgeGlowLeft.isFinished()) { 589 mEdgeGlowLeft.onRelease(); 590 } 591 } 592 if (mEdgeGlowLeft != null 593 && (!mEdgeGlowLeft.isFinished() || !mEdgeGlowRight.isFinished())) { 594 invalidate(); 595 } 596 } 597 } 598 break; 599 case MotionEvent.ACTION_UP: 600 if (mIsBeingDragged) { 601 final VelocityTracker velocityTracker = mVelocityTracker; 602 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 603 int initialVelocity = (int) velocityTracker.getXVelocity(mActivePointerId); 604 605 if (getChildCount() > 0) { 606 if ((Math.abs(initialVelocity) > mMinimumVelocity)) { 607 fling(-initialVelocity); 608 } else { 609 if (mScroller.springBack(mScrollX, mScrollY, 0, 610 getScrollRange(), 0, 0)) { 611 invalidate(); 612 } 613 } 614 } 615 616 mActivePointerId = INVALID_POINTER; 617 mIsBeingDragged = false; 618 recycleVelocityTracker(); 619 620 if (mEdgeGlowLeft != null) { 621 mEdgeGlowLeft.onRelease(); 622 mEdgeGlowRight.onRelease(); 623 } 624 } 625 break; 626 case MotionEvent.ACTION_CANCEL: 627 if (mIsBeingDragged && getChildCount() > 0) { 628 if (mScroller.springBack(mScrollX, mScrollY, 0, getScrollRange(), 0, 0)) { 629 invalidate(); 630 } 631 mActivePointerId = INVALID_POINTER; 632 mIsBeingDragged = false; 633 recycleVelocityTracker(); 634 635 if (mEdgeGlowLeft != null) { 636 mEdgeGlowLeft.onRelease(); 637 mEdgeGlowRight.onRelease(); 638 } 639 } 640 break; 641 case MotionEvent.ACTION_POINTER_UP: 642 onSecondaryPointerUp(ev); 643 break; 644 } 645 return true; 646 } 647 648 private void onSecondaryPointerUp(MotionEvent ev) { 649 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> 650 MotionEvent.ACTION_POINTER_INDEX_SHIFT; 651 final int pointerId = ev.getPointerId(pointerIndex); 652 if (pointerId == mActivePointerId) { 653 // This was our active pointer going up. Choose a new 654 // active pointer and adjust accordingly. 655 // TODO: Make this decision more intelligent. 656 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 657 mLastMotionX = ev.getX(newPointerIndex); 658 mActivePointerId = ev.getPointerId(newPointerIndex); 659 if (mVelocityTracker != null) { 660 mVelocityTracker.clear(); 661 } 662 } 663 } 664 665 @Override 666 public boolean onGenericMotionEvent(MotionEvent event) { 667 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 668 switch (event.getAction()) { 669 case MotionEvent.ACTION_SCROLL: { 670 if (!mIsBeingDragged) { 671 final float hscroll; 672 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) { 673 hscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL); 674 } else { 675 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); 676 } 677 if (hscroll != 0) { 678 final int delta = (int) (hscroll * getHorizontalScrollFactor()); 679 final int range = getScrollRange(); 680 int oldScrollX = mScrollX; 681 int newScrollX = oldScrollX + delta; 682 if (newScrollX < 0) { 683 newScrollX = 0; 684 } else if (newScrollX > range) { 685 newScrollX = range; 686 } 687 if (newScrollX != oldScrollX) { 688 super.scrollTo(newScrollX, mScrollY); 689 return true; 690 } 691 } 692 } 693 } 694 } 695 } 696 return super.onGenericMotionEvent(event); 697 } 698 699 @Override 700 protected void onOverScrolled(int scrollX, int scrollY, 701 boolean clampedX, boolean clampedY) { 702 // Treat animating scrolls differently; see #computeScroll() for why. 703 if (!mScroller.isFinished()) { 704 mScrollX = scrollX; 705 mScrollY = scrollY; 706 invalidateParentIfNeeded(); 707 if (clampedX) { 708 mScroller.springBack(mScrollX, mScrollY, 0, getScrollRange(), 0, 0); 709 } 710 } else { 711 super.scrollTo(scrollX, scrollY); 712 } 713 awakenScrollBars(); 714 } 715 716 @Override 717 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 718 super.onInitializeAccessibilityNodeInfo(info); 719 info.setScrollable(true); 720 } 721 722 @Override 723 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 724 super.onInitializeAccessibilityEvent(event); 725 event.setScrollable(true); 726 } 727 728 @Override 729 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 730 // Do not append text content to scroll events they are fired frequently 731 // and the client has already received another event type with the text. 732 if (event.getEventType() != AccessibilityEvent.TYPE_VIEW_SCROLLED) { 733 super.dispatchPopulateAccessibilityEvent(event); 734 } 735 return false; 736 } 737 738 private int getScrollRange() { 739 int scrollRange = 0; 740 if (getChildCount() > 0) { 741 View child = getChildAt(0); 742 scrollRange = Math.max(0, 743 child.getWidth() - (getWidth() - mPaddingLeft - mPaddingRight)); 744 } 745 return scrollRange; 746 } 747 748 /** 749 * <p> 750 * Finds the next focusable component that fits in this View's bounds 751 * (excluding fading edges) pretending that this View's left is located at 752 * the parameter left. 753 * </p> 754 * 755 * @param leftFocus look for a candidate is the one at the left of the bounds 756 * if leftFocus is true, or at the right of the bounds if leftFocus 757 * is false 758 * @param left the left offset of the bounds in which a focusable must be 759 * found (the fading edge is assumed to start at this position) 760 * @param preferredFocusable the View that has highest priority and will be 761 * returned if it is within my bounds (null is valid) 762 * @return the next focusable component in the bounds or null if none can be found 763 */ 764 private View findFocusableViewInMyBounds(final boolean leftFocus, 765 final int left, View preferredFocusable) { 766 /* 767 * The fading edge's transparent side should be considered for focus 768 * since it's mostly visible, so we divide the actual fading edge length 769 * by 2. 770 */ 771 final int fadingEdgeLength = getHorizontalFadingEdgeLength() / 2; 772 final int leftWithoutFadingEdge = left + fadingEdgeLength; 773 final int rightWithoutFadingEdge = left + getWidth() - fadingEdgeLength; 774 775 if ((preferredFocusable != null) 776 && (preferredFocusable.getLeft() < rightWithoutFadingEdge) 777 && (preferredFocusable.getRight() > leftWithoutFadingEdge)) { 778 return preferredFocusable; 779 } 780 781 return findFocusableViewInBounds(leftFocus, leftWithoutFadingEdge, 782 rightWithoutFadingEdge); 783 } 784 785 /** 786 * <p> 787 * Finds the next focusable component that fits in the specified bounds. 788 * </p> 789 * 790 * @param leftFocus look for a candidate is the one at the left of the bounds 791 * if leftFocus is true, or at the right of the bounds if 792 * leftFocus is false 793 * @param left the left offset of the bounds in which a focusable must be 794 * found 795 * @param right the right offset of the bounds in which a focusable must 796 * be found 797 * @return the next focusable component in the bounds or null if none can 798 * be found 799 */ 800 private View findFocusableViewInBounds(boolean leftFocus, int left, int right) { 801 802 List<View> focusables = getFocusables(View.FOCUS_FORWARD); 803 View focusCandidate = null; 804 805 /* 806 * A fully contained focusable is one where its left is below the bound's 807 * left, and its right is above the bound's right. A partially 808 * contained focusable is one where some part of it is within the 809 * bounds, but it also has some part that is not within bounds. A fully contained 810 * focusable is preferred to a partially contained focusable. 811 */ 812 boolean foundFullyContainedFocusable = false; 813 814 int count = focusables.size(); 815 for (int i = 0; i < count; i++) { 816 View view = focusables.get(i); 817 int viewLeft = view.getLeft(); 818 int viewRight = view.getRight(); 819 820 if (left < viewRight && viewLeft < right) { 821 /* 822 * the focusable is in the target area, it is a candidate for 823 * focusing 824 */ 825 826 final boolean viewIsFullyContained = (left < viewLeft) && 827 (viewRight < right); 828 829 if (focusCandidate == null) { 830 /* No candidate, take this one */ 831 focusCandidate = view; 832 foundFullyContainedFocusable = viewIsFullyContained; 833 } else { 834 final boolean viewIsCloserToBoundary = 835 (leftFocus && viewLeft < focusCandidate.getLeft()) || 836 (!leftFocus && viewRight > focusCandidate.getRight()); 837 838 if (foundFullyContainedFocusable) { 839 if (viewIsFullyContained && viewIsCloserToBoundary) { 840 /* 841 * We're dealing with only fully contained views, so 842 * it has to be closer to the boundary to beat our 843 * candidate 844 */ 845 focusCandidate = view; 846 } 847 } else { 848 if (viewIsFullyContained) { 849 /* Any fully contained view beats a partially contained view */ 850 focusCandidate = view; 851 foundFullyContainedFocusable = true; 852 } else if (viewIsCloserToBoundary) { 853 /* 854 * Partially contained view beats another partially 855 * contained view if it's closer 856 */ 857 focusCandidate = view; 858 } 859 } 860 } 861 } 862 } 863 864 return focusCandidate; 865 } 866 867 /** 868 * <p>Handles scrolling in response to a "page up/down" shortcut press. This 869 * method will scroll the view by one page left or right and give the focus 870 * to the leftmost/rightmost component in the new visible area. If no 871 * component is a good candidate for focus, this scrollview reclaims the 872 * focus.</p> 873 * 874 * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} 875 * to go one page left or {@link android.view.View#FOCUS_RIGHT} 876 * to go one page right 877 * @return true if the key event is consumed by this method, false otherwise 878 */ 879 public boolean pageScroll(int direction) { 880 boolean right = direction == View.FOCUS_RIGHT; 881 int width = getWidth(); 882 883 if (right) { 884 mTempRect.left = getScrollX() + width; 885 int count = getChildCount(); 886 if (count > 0) { 887 View view = getChildAt(0); 888 if (mTempRect.left + width > view.getRight()) { 889 mTempRect.left = view.getRight() - width; 890 } 891 } 892 } else { 893 mTempRect.left = getScrollX() - width; 894 if (mTempRect.left < 0) { 895 mTempRect.left = 0; 896 } 897 } 898 mTempRect.right = mTempRect.left + width; 899 900 return scrollAndFocus(direction, mTempRect.left, mTempRect.right); 901 } 902 903 /** 904 * <p>Handles scrolling in response to a "home/end" shortcut press. This 905 * method will scroll the view to the left or right and give the focus 906 * to the leftmost/rightmost component in the new visible area. If no 907 * component is a good candidate for focus, this scrollview reclaims the 908 * focus.</p> 909 * 910 * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} 911 * to go the left of the view or {@link android.view.View#FOCUS_RIGHT} 912 * to go the right 913 * @return true if the key event is consumed by this method, false otherwise 914 */ 915 public boolean fullScroll(int direction) { 916 boolean right = direction == View.FOCUS_RIGHT; 917 int width = getWidth(); 918 919 mTempRect.left = 0; 920 mTempRect.right = width; 921 922 if (right) { 923 int count = getChildCount(); 924 if (count > 0) { 925 View view = getChildAt(0); 926 mTempRect.right = view.getRight(); 927 mTempRect.left = mTempRect.right - width; 928 } 929 } 930 931 return scrollAndFocus(direction, mTempRect.left, mTempRect.right); 932 } 933 934 /** 935 * <p>Scrolls the view to make the area defined by <code>left</code> and 936 * <code>right</code> visible. This method attempts to give the focus 937 * to a component visible in this area. If no component can be focused in 938 * the new visible area, the focus is reclaimed by this scrollview.</p> 939 * 940 * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} 941 * to go left {@link android.view.View#FOCUS_RIGHT} to right 942 * @param left the left offset of the new area to be made visible 943 * @param right the right offset of the new area to be made visible 944 * @return true if the key event is consumed by this method, false otherwise 945 */ 946 private boolean scrollAndFocus(int direction, int left, int right) { 947 boolean handled = true; 948 949 int width = getWidth(); 950 int containerLeft = getScrollX(); 951 int containerRight = containerLeft + width; 952 boolean goLeft = direction == View.FOCUS_LEFT; 953 954 View newFocused = findFocusableViewInBounds(goLeft, left, right); 955 if (newFocused == null) { 956 newFocused = this; 957 } 958 959 if (left >= containerLeft && right <= containerRight) { 960 handled = false; 961 } else { 962 int delta = goLeft ? (left - containerLeft) : (right - containerRight); 963 doScrollX(delta); 964 } 965 966 if (newFocused != findFocus()) newFocused.requestFocus(direction); 967 968 return handled; 969 } 970 971 /** 972 * Handle scrolling in response to a left or right arrow click. 973 * 974 * @param direction The direction corresponding to the arrow key that was 975 * pressed 976 * @return True if we consumed the event, false otherwise 977 */ 978 public boolean arrowScroll(int direction) { 979 980 View currentFocused = findFocus(); 981 if (currentFocused == this) currentFocused = null; 982 983 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); 984 985 final int maxJump = getMaxScrollAmount(); 986 987 if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump)) { 988 nextFocused.getDrawingRect(mTempRect); 989 offsetDescendantRectToMyCoords(nextFocused, mTempRect); 990 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 991 doScrollX(scrollDelta); 992 nextFocused.requestFocus(direction); 993 } else { 994 // no new focus 995 int scrollDelta = maxJump; 996 997 if (direction == View.FOCUS_LEFT && getScrollX() < scrollDelta) { 998 scrollDelta = getScrollX(); 999 } else if (direction == View.FOCUS_RIGHT && getChildCount() > 0) { 1000 1001 int daRight = getChildAt(0).getRight(); 1002 1003 int screenRight = getScrollX() + getWidth(); 1004 1005 if (daRight - screenRight < maxJump) { 1006 scrollDelta = daRight - screenRight; 1007 } 1008 } 1009 if (scrollDelta == 0) { 1010 return false; 1011 } 1012 doScrollX(direction == View.FOCUS_RIGHT ? scrollDelta : -scrollDelta); 1013 } 1014 1015 if (currentFocused != null && currentFocused.isFocused() 1016 && isOffScreen(currentFocused)) { 1017 // previously focused item still has focus and is off screen, give 1018 // it up (take it back to ourselves) 1019 // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are 1020 // sure to 1021 // get it) 1022 final int descendantFocusability = getDescendantFocusability(); // save 1023 setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); 1024 requestFocus(); 1025 setDescendantFocusability(descendantFocusability); // restore 1026 } 1027 return true; 1028 } 1029 1030 /** 1031 * @return whether the descendant of this scroll view is scrolled off 1032 * screen. 1033 */ 1034 private boolean isOffScreen(View descendant) { 1035 return !isWithinDeltaOfScreen(descendant, 0); 1036 } 1037 1038 /** 1039 * @return whether the descendant of this scroll view is within delta 1040 * pixels of being on the screen. 1041 */ 1042 private boolean isWithinDeltaOfScreen(View descendant, int delta) { 1043 descendant.getDrawingRect(mTempRect); 1044 offsetDescendantRectToMyCoords(descendant, mTempRect); 1045 1046 return (mTempRect.right + delta) >= getScrollX() 1047 && (mTempRect.left - delta) <= (getScrollX() + getWidth()); 1048 } 1049 1050 /** 1051 * Smooth scroll by a X delta 1052 * 1053 * @param delta the number of pixels to scroll by on the X axis 1054 */ 1055 private void doScrollX(int delta) { 1056 if (delta != 0) { 1057 if (mSmoothScrollingEnabled) { 1058 smoothScrollBy(delta, 0); 1059 } else { 1060 scrollBy(delta, 0); 1061 } 1062 } 1063 } 1064 1065 /** 1066 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 1067 * 1068 * @param dx the number of pixels to scroll by on the X axis 1069 * @param dy the number of pixels to scroll by on the Y axis 1070 */ 1071 public final void smoothScrollBy(int dx, int dy) { 1072 if (getChildCount() == 0) { 1073 // Nothing to do. 1074 return; 1075 } 1076 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 1077 if (duration > ANIMATED_SCROLL_GAP) { 1078 final int width = getWidth() - mPaddingRight - mPaddingLeft; 1079 final int right = getChildAt(0).getWidth(); 1080 final int maxX = Math.max(0, right - width); 1081 final int scrollX = mScrollX; 1082 dx = Math.max(0, Math.min(scrollX + dx, maxX)) - scrollX; 1083 1084 mScroller.startScroll(scrollX, mScrollY, dx, 0); 1085 invalidate(); 1086 } else { 1087 if (!mScroller.isFinished()) { 1088 mScroller.abortAnimation(); 1089 } 1090 scrollBy(dx, dy); 1091 } 1092 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 1093 } 1094 1095 /** 1096 * Like {@link #scrollTo}, but scroll smoothly instead of immediately. 1097 * 1098 * @param x the position where to scroll on the X axis 1099 * @param y the position where to scroll on the Y axis 1100 */ 1101 public final void smoothScrollTo(int x, int y) { 1102 smoothScrollBy(x - mScrollX, y - mScrollY); 1103 } 1104 1105 /** 1106 * <p>The scroll range of a scroll view is the overall width of all of its 1107 * children.</p> 1108 */ 1109 @Override 1110 protected int computeHorizontalScrollRange() { 1111 final int count = getChildCount(); 1112 final int contentWidth = getWidth() - mPaddingLeft - mPaddingRight; 1113 if (count == 0) { 1114 return contentWidth; 1115 } 1116 1117 int scrollRange = getChildAt(0).getRight(); 1118 final int scrollX = mScrollX; 1119 final int overscrollRight = Math.max(0, scrollRange - contentWidth); 1120 if (scrollX < 0) { 1121 scrollRange -= scrollX; 1122 } else if (scrollX > overscrollRight) { 1123 scrollRange += scrollX - overscrollRight; 1124 } 1125 1126 return scrollRange; 1127 } 1128 1129 @Override 1130 protected int computeHorizontalScrollOffset() { 1131 return Math.max(0, super.computeHorizontalScrollOffset()); 1132 } 1133 1134 @Override 1135 protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { 1136 ViewGroup.LayoutParams lp = child.getLayoutParams(); 1137 1138 int childWidthMeasureSpec; 1139 int childHeightMeasureSpec; 1140 1141 childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop 1142 + mPaddingBottom, lp.height); 1143 1144 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 1145 1146 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1147 } 1148 1149 @Override 1150 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 1151 int parentHeightMeasureSpec, int heightUsed) { 1152 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 1153 1154 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 1155 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin 1156 + heightUsed, lp.height); 1157 final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( 1158 lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED); 1159 1160 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1161 } 1162 1163 @Override 1164 public void computeScroll() { 1165 if (mScroller.computeScrollOffset()) { 1166 // This is called at drawing time by ViewGroup. We don't want to 1167 // re-show the scrollbars at this point, which scrollTo will do, 1168 // so we replicate most of scrollTo here. 1169 // 1170 // It's a little odd to call onScrollChanged from inside the drawing. 1171 // 1172 // It is, except when you remember that computeScroll() is used to 1173 // animate scrolling. So unless we want to defer the onScrollChanged() 1174 // until the end of the animated scrolling, we don't really have a 1175 // choice here. 1176 // 1177 // I agree. The alternative, which I think would be worse, is to post 1178 // something and tell the subclasses later. This is bad because there 1179 // will be a window where mScrollX/Y is different from what the app 1180 // thinks it is. 1181 // 1182 int oldX = mScrollX; 1183 int oldY = mScrollY; 1184 int x = mScroller.getCurrX(); 1185 int y = mScroller.getCurrY(); 1186 1187 if (oldX != x || oldY != y) { 1188 final int range = getScrollRange(); 1189 final int overscrollMode = getOverScrollMode(); 1190 final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS || 1191 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); 1192 1193 overScrollBy(x - oldX, y - oldY, oldX, oldY, range, 0, 1194 mOverflingDistance, 0, false); 1195 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 1196 1197 if (canOverscroll) { 1198 if (x < 0 && oldX >= 0) { 1199 mEdgeGlowLeft.onAbsorb((int) mScroller.getCurrVelocity()); 1200 } else if (x > range && oldX <= range) { 1201 mEdgeGlowRight.onAbsorb((int) mScroller.getCurrVelocity()); 1202 } 1203 } 1204 } 1205 1206 awakenScrollBars(); 1207 1208 // Keep on drawing until the animation has finished. 1209 postInvalidate(); 1210 } 1211 } 1212 1213 /** 1214 * Scrolls the view to the given child. 1215 * 1216 * @param child the View to scroll to 1217 */ 1218 private void scrollToChild(View child) { 1219 child.getDrawingRect(mTempRect); 1220 1221 /* Offset from child's local coordinates to ScrollView coordinates */ 1222 offsetDescendantRectToMyCoords(child, mTempRect); 1223 1224 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1225 1226 if (scrollDelta != 0) { 1227 scrollBy(scrollDelta, 0); 1228 } 1229 } 1230 1231 /** 1232 * If rect is off screen, scroll just enough to get it (or at least the 1233 * first screen size chunk of it) on screen. 1234 * 1235 * @param rect The rectangle. 1236 * @param immediate True to scroll immediately without animation 1237 * @return true if scrolling was performed 1238 */ 1239 private boolean scrollToChildRect(Rect rect, boolean immediate) { 1240 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); 1241 final boolean scroll = delta != 0; 1242 if (scroll) { 1243 if (immediate) { 1244 scrollBy(delta, 0); 1245 } else { 1246 smoothScrollBy(delta, 0); 1247 } 1248 } 1249 return scroll; 1250 } 1251 1252 /** 1253 * Compute the amount to scroll in the X direction in order to get 1254 * a rectangle completely on the screen (or, if taller than the screen, 1255 * at least the first screen size chunk of it). 1256 * 1257 * @param rect The rect. 1258 * @return The scroll delta. 1259 */ 1260 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { 1261 if (getChildCount() == 0) return 0; 1262 1263 int width = getWidth(); 1264 int screenLeft = getScrollX(); 1265 int screenRight = screenLeft + width; 1266 1267 int fadingEdge = getHorizontalFadingEdgeLength(); 1268 1269 // leave room for left fading edge as long as rect isn't at very left 1270 if (rect.left > 0) { 1271 screenLeft += fadingEdge; 1272 } 1273 1274 // leave room for right fading edge as long as rect isn't at very right 1275 if (rect.right < getChildAt(0).getWidth()) { 1276 screenRight -= fadingEdge; 1277 } 1278 1279 int scrollXDelta = 0; 1280 1281 if (rect.right > screenRight && rect.left > screenLeft) { 1282 // need to move right to get it in view: move right just enough so 1283 // that the entire rectangle is in view (or at least the first 1284 // screen size chunk). 1285 1286 if (rect.width() > width) { 1287 // just enough to get screen size chunk on 1288 scrollXDelta += (rect.left - screenLeft); 1289 } else { 1290 // get entire rect at right of screen 1291 scrollXDelta += (rect.right - screenRight); 1292 } 1293 1294 // make sure we aren't scrolling beyond the end of our content 1295 int right = getChildAt(0).getRight(); 1296 int distanceToRight = right - screenRight; 1297 scrollXDelta = Math.min(scrollXDelta, distanceToRight); 1298 1299 } else if (rect.left < screenLeft && rect.right < screenRight) { 1300 // need to move right to get it in view: move right just enough so that 1301 // entire rectangle is in view (or at least the first screen 1302 // size chunk of it). 1303 1304 if (rect.width() > width) { 1305 // screen size chunk 1306 scrollXDelta -= (screenRight - rect.right); 1307 } else { 1308 // entire rect at left 1309 scrollXDelta -= (screenLeft - rect.left); 1310 } 1311 1312 // make sure we aren't scrolling any further than the left our content 1313 scrollXDelta = Math.max(scrollXDelta, -getScrollX()); 1314 } 1315 return scrollXDelta; 1316 } 1317 1318 @Override 1319 public void requestChildFocus(View child, View focused) { 1320 if (!mIsLayoutDirty) { 1321 scrollToChild(focused); 1322 } else { 1323 // The child may not be laid out yet, we can't compute the scroll yet 1324 mChildToScrollTo = focused; 1325 } 1326 super.requestChildFocus(child, focused); 1327 } 1328 1329 1330 /** 1331 * When looking for focus in children of a scroll view, need to be a little 1332 * more careful not to give focus to something that is scrolled off screen. 1333 * 1334 * This is more expensive than the default {@link android.view.ViewGroup} 1335 * implementation, otherwise this behavior might have been made the default. 1336 */ 1337 @Override 1338 protected boolean onRequestFocusInDescendants(int direction, 1339 Rect previouslyFocusedRect) { 1340 1341 // convert from forward / backward notation to up / down / left / right 1342 // (ugh). 1343 if (direction == View.FOCUS_FORWARD) { 1344 direction = View.FOCUS_RIGHT; 1345 } else if (direction == View.FOCUS_BACKWARD) { 1346 direction = View.FOCUS_LEFT; 1347 } 1348 1349 final View nextFocus = previouslyFocusedRect == null ? 1350 FocusFinder.getInstance().findNextFocus(this, null, direction) : 1351 FocusFinder.getInstance().findNextFocusFromRect(this, 1352 previouslyFocusedRect, direction); 1353 1354 if (nextFocus == null) { 1355 return false; 1356 } 1357 1358 if (isOffScreen(nextFocus)) { 1359 return false; 1360 } 1361 1362 return nextFocus.requestFocus(direction, previouslyFocusedRect); 1363 } 1364 1365 @Override 1366 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 1367 boolean immediate) { 1368 // offset into coordinate space of this scroll view 1369 rectangle.offset(child.getLeft() - child.getScrollX(), 1370 child.getTop() - child.getScrollY()); 1371 1372 return scrollToChildRect(rectangle, immediate); 1373 } 1374 1375 @Override 1376 public void requestLayout() { 1377 mIsLayoutDirty = true; 1378 super.requestLayout(); 1379 } 1380 1381 @Override 1382 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1383 super.onLayout(changed, l, t, r, b); 1384 mIsLayoutDirty = false; 1385 // Give a child focus if it needs it 1386 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { 1387 scrollToChild(mChildToScrollTo); 1388 } 1389 mChildToScrollTo = null; 1390 1391 // Calling this with the present values causes it to re-clam them 1392 scrollTo(mScrollX, mScrollY); 1393 } 1394 1395 @Override 1396 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1397 super.onSizeChanged(w, h, oldw, oldh); 1398 1399 View currentFocused = findFocus(); 1400 if (null == currentFocused || this == currentFocused) 1401 return; 1402 1403 final int maxJump = mRight - mLeft; 1404 1405 if (isWithinDeltaOfScreen(currentFocused, maxJump)) { 1406 currentFocused.getDrawingRect(mTempRect); 1407 offsetDescendantRectToMyCoords(currentFocused, mTempRect); 1408 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1409 doScrollX(scrollDelta); 1410 } 1411 } 1412 1413 /** 1414 * Return true if child is an descendant of parent, (or equal to the parent). 1415 */ 1416 private boolean isViewDescendantOf(View child, View parent) { 1417 if (child == parent) { 1418 return true; 1419 } 1420 1421 final ViewParent theParent = child.getParent(); 1422 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 1423 } 1424 1425 /** 1426 * Fling the scroll view 1427 * 1428 * @param velocityX The initial velocity in the X direction. Positive 1429 * numbers mean that the finger/curor is moving down the screen, 1430 * which means we want to scroll towards the left. 1431 */ 1432 public void fling(int velocityX) { 1433 if (getChildCount() > 0) { 1434 int width = getWidth() - mPaddingRight - mPaddingLeft; 1435 int right = getChildAt(0).getWidth(); 1436 1437 mScroller.fling(mScrollX, mScrollY, velocityX, 0, 0, 1438 Math.max(0, right - width), 0, 0, width/2, 0); 1439 1440 final boolean movingRight = velocityX > 0; 1441 1442 View currentFocused = findFocus(); 1443 View newFocused = findFocusableViewInMyBounds(movingRight, 1444 mScroller.getFinalX(), currentFocused); 1445 1446 if (newFocused == null) { 1447 newFocused = this; 1448 } 1449 1450 if (newFocused != currentFocused) { 1451 newFocused.requestFocus(movingRight ? View.FOCUS_RIGHT : View.FOCUS_LEFT); 1452 } 1453 1454 invalidate(); 1455 } 1456 } 1457 1458 /** 1459 * {@inheritDoc} 1460 * 1461 * <p>This version also clamps the scrolling to the bounds of our child. 1462 */ 1463 @Override 1464 public void scrollTo(int x, int y) { 1465 // we rely on the fact the View.scrollBy calls scrollTo. 1466 if (getChildCount() > 0) { 1467 View child = getChildAt(0); 1468 x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); 1469 y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); 1470 if (x != mScrollX || y != mScrollY) { 1471 super.scrollTo(x, y); 1472 } 1473 } 1474 } 1475 1476 @Override 1477 public void setOverScrollMode(int mode) { 1478 if (mode != OVER_SCROLL_NEVER) { 1479 if (mEdgeGlowLeft == null) { 1480 Context context = getContext(); 1481 mEdgeGlowLeft = new EdgeEffect(context); 1482 mEdgeGlowRight = new EdgeEffect(context); 1483 } 1484 } else { 1485 mEdgeGlowLeft = null; 1486 mEdgeGlowRight = null; 1487 } 1488 super.setOverScrollMode(mode); 1489 } 1490 1491 @SuppressWarnings({"SuspiciousNameCombination"}) 1492 @Override 1493 public void draw(Canvas canvas) { 1494 super.draw(canvas); 1495 if (mEdgeGlowLeft != null) { 1496 final int scrollX = mScrollX; 1497 if (!mEdgeGlowLeft.isFinished()) { 1498 final int restoreCount = canvas.save(); 1499 final int height = getHeight() - mPaddingTop - mPaddingBottom; 1500 1501 canvas.rotate(270); 1502 canvas.translate(-height + mPaddingTop, Math.min(0, scrollX)); 1503 mEdgeGlowLeft.setSize(height, getWidth()); 1504 if (mEdgeGlowLeft.draw(canvas)) { 1505 invalidate(); 1506 } 1507 canvas.restoreToCount(restoreCount); 1508 } 1509 if (!mEdgeGlowRight.isFinished()) { 1510 final int restoreCount = canvas.save(); 1511 final int width = getWidth(); 1512 final int height = getHeight() - mPaddingTop - mPaddingBottom; 1513 1514 canvas.rotate(90); 1515 canvas.translate(-mPaddingTop, 1516 -(Math.max(getScrollRange(), scrollX) + width)); 1517 mEdgeGlowRight.setSize(height, width); 1518 if (mEdgeGlowRight.draw(canvas)) { 1519 invalidate(); 1520 } 1521 canvas.restoreToCount(restoreCount); 1522 } 1523 } 1524 } 1525 1526 private int clamp(int n, int my, int child) { 1527 if (my >= child || n < 0) { 1528 return 0; 1529 } 1530 if ((my + n) > child) { 1531 return child - my; 1532 } 1533 return n; 1534 } 1535} 1536