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