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