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