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