HorizontalScrollView.java revision 0b8bb4282a7d1afb24f8c4d5beb2ca4ecc731116
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 int count = getChildCount(); 894 if (count == 0) { 895 return getWidth(); 896 } 897 898 int scrollRange = getChildAt(0).getRight(); 899 int scrollX = mScrollX; 900 int overscrollRight = scrollRange - getWidth() - mPaddingLeft - mPaddingRight; 901 if (scrollX < 0) { 902 scrollRange -= scrollX; 903 } else if (scrollX > overscrollRight) { 904 scrollRange += scrollX - overscrollRight; 905 } 906 907 return scrollRange; 908 } 909 910 @Override 911 protected int computeHorizontalScrollOffset() { 912 return Math.max(0, super.computeHorizontalScrollOffset()); 913 } 914 915 @Override 916 protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { 917 ViewGroup.LayoutParams lp = child.getLayoutParams(); 918 919 int childWidthMeasureSpec; 920 int childHeightMeasureSpec; 921 922 childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop 923 + mPaddingBottom, lp.height); 924 925 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 926 927 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 928 } 929 930 @Override 931 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 932 int parentHeightMeasureSpec, int heightUsed) { 933 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 934 935 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 936 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin 937 + heightUsed, lp.height); 938 final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( 939 lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED); 940 941 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 942 } 943 944 @Override 945 public void computeScroll() { 946 if (mScroller.computeScrollOffset()) { 947 // This is called at drawing time by ViewGroup. We don't want to 948 // re-show the scrollbars at this point, which scrollTo will do, 949 // so we replicate most of scrollTo here. 950 // 951 // It's a little odd to call onScrollChanged from inside the drawing. 952 // 953 // It is, except when you remember that computeScroll() is used to 954 // animate scrolling. So unless we want to defer the onScrollChanged() 955 // until the end of the animated scrolling, we don't really have a 956 // choice here. 957 // 958 // I agree. The alternative, which I think would be worse, is to post 959 // something and tell the subclasses later. This is bad because there 960 // will be a window where mScrollX/Y is different from what the app 961 // thinks it is. 962 // 963 int oldX = mScrollX; 964 int oldY = mScrollY; 965 int x = mScroller.getCurrX(); 966 int y = mScroller.getCurrY(); 967 968 if (oldX != x || oldY != y) { 969 overscrollBy(x - oldX, y - oldY, oldX, oldY, getScrollRange(), 0, 970 getOverscrollMax(), 0); 971 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 972 } 973 974 // Keep on drawing until the animation has finished. 975 postInvalidate(); 976 } 977 } 978 979 /** 980 * Scrolls the view to the given child. 981 * 982 * @param child the View to scroll to 983 */ 984 private void scrollToChild(View child) { 985 child.getDrawingRect(mTempRect); 986 987 /* Offset from child's local coordinates to ScrollView coordinates */ 988 offsetDescendantRectToMyCoords(child, mTempRect); 989 990 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 991 992 if (scrollDelta != 0) { 993 scrollBy(scrollDelta, 0); 994 } 995 } 996 997 /** 998 * If rect is off screen, scroll just enough to get it (or at least the 999 * first screen size chunk of it) on screen. 1000 * 1001 * @param rect The rectangle. 1002 * @param immediate True to scroll immediately without animation 1003 * @return true if scrolling was performed 1004 */ 1005 private boolean scrollToChildRect(Rect rect, boolean immediate) { 1006 final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); 1007 final boolean scroll = delta != 0; 1008 if (scroll) { 1009 if (immediate) { 1010 scrollBy(delta, 0); 1011 } else { 1012 smoothScrollBy(delta, 0); 1013 } 1014 } 1015 return scroll; 1016 } 1017 1018 /** 1019 * Compute the amount to scroll in the X direction in order to get 1020 * a rectangle completely on the screen (or, if taller than the screen, 1021 * at least the first screen size chunk of it). 1022 * 1023 * @param rect The rect. 1024 * @return The scroll delta. 1025 */ 1026 protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { 1027 if (getChildCount() == 0) return 0; 1028 1029 int width = getWidth(); 1030 int screenLeft = getScrollX(); 1031 int screenRight = screenLeft + width; 1032 1033 int fadingEdge = getHorizontalFadingEdgeLength(); 1034 1035 // leave room for left fading edge as long as rect isn't at very left 1036 if (rect.left > 0) { 1037 screenLeft += fadingEdge; 1038 } 1039 1040 // leave room for right fading edge as long as rect isn't at very right 1041 if (rect.right < getChildAt(0).getWidth()) { 1042 screenRight -= fadingEdge; 1043 } 1044 1045 int scrollXDelta = 0; 1046 1047 if (rect.right > screenRight && rect.left > screenLeft) { 1048 // need to move right to get it in view: move right just enough so 1049 // that the entire rectangle is in view (or at least the first 1050 // screen size chunk). 1051 1052 if (rect.width() > width) { 1053 // just enough to get screen size chunk on 1054 scrollXDelta += (rect.left - screenLeft); 1055 } else { 1056 // get entire rect at right of screen 1057 scrollXDelta += (rect.right - screenRight); 1058 } 1059 1060 // make sure we aren't scrolling beyond the end of our content 1061 int right = getChildAt(0).getRight(); 1062 int distanceToRight = right - screenRight; 1063 scrollXDelta = Math.min(scrollXDelta, distanceToRight); 1064 1065 } else if (rect.left < screenLeft && rect.right < screenRight) { 1066 // need to move right to get it in view: move right just enough so that 1067 // entire rectangle is in view (or at least the first screen 1068 // size chunk of it). 1069 1070 if (rect.width() > width) { 1071 // screen size chunk 1072 scrollXDelta -= (screenRight - rect.right); 1073 } else { 1074 // entire rect at left 1075 scrollXDelta -= (screenLeft - rect.left); 1076 } 1077 1078 // make sure we aren't scrolling any further than the left our content 1079 scrollXDelta = Math.max(scrollXDelta, -getScrollX()); 1080 } 1081 return scrollXDelta; 1082 } 1083 1084 @Override 1085 public void requestChildFocus(View child, View focused) { 1086 if (!mScrollViewMovedFocus) { 1087 if (!mIsLayoutDirty) { 1088 scrollToChild(focused); 1089 } else { 1090 // The child may not be laid out yet, we can't compute the scroll yet 1091 mChildToScrollTo = focused; 1092 } 1093 } 1094 super.requestChildFocus(child, focused); 1095 } 1096 1097 1098 /** 1099 * When looking for focus in children of a scroll view, need to be a little 1100 * more careful not to give focus to something that is scrolled off screen. 1101 * 1102 * This is more expensive than the default {@link android.view.ViewGroup} 1103 * implementation, otherwise this behavior might have been made the default. 1104 */ 1105 @Override 1106 protected boolean onRequestFocusInDescendants(int direction, 1107 Rect previouslyFocusedRect) { 1108 1109 // convert from forward / backward notation to up / down / left / right 1110 // (ugh). 1111 if (direction == View.FOCUS_FORWARD) { 1112 direction = View.FOCUS_RIGHT; 1113 } else if (direction == View.FOCUS_BACKWARD) { 1114 direction = View.FOCUS_LEFT; 1115 } 1116 1117 final View nextFocus = previouslyFocusedRect == null ? 1118 FocusFinder.getInstance().findNextFocus(this, null, direction) : 1119 FocusFinder.getInstance().findNextFocusFromRect(this, 1120 previouslyFocusedRect, direction); 1121 1122 if (nextFocus == null) { 1123 return false; 1124 } 1125 1126 if (isOffScreen(nextFocus)) { 1127 return false; 1128 } 1129 1130 return nextFocus.requestFocus(direction, previouslyFocusedRect); 1131 } 1132 1133 @Override 1134 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 1135 boolean immediate) { 1136 // offset into coordinate space of this scroll view 1137 rectangle.offset(child.getLeft() - child.getScrollX(), 1138 child.getTop() - child.getScrollY()); 1139 1140 return scrollToChildRect(rectangle, immediate); 1141 } 1142 1143 @Override 1144 public void requestLayout() { 1145 mIsLayoutDirty = true; 1146 super.requestLayout(); 1147 } 1148 1149 @Override 1150 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1151 super.onLayout(changed, l, t, r, b); 1152 mIsLayoutDirty = false; 1153 // Give a child focus if it needs it 1154 if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { 1155 scrollToChild(mChildToScrollTo); 1156 } 1157 mChildToScrollTo = null; 1158 1159 // Calling this with the present values causes it to re-clam them 1160 scrollTo(mScrollX, mScrollY); 1161 } 1162 1163 @Override 1164 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1165 super.onSizeChanged(w, h, oldw, oldh); 1166 1167 View currentFocused = findFocus(); 1168 if (null == currentFocused || this == currentFocused) 1169 return; 1170 1171 final int maxJump = mRight - mLeft; 1172 1173 if (isWithinDeltaOfScreen(currentFocused, maxJump)) { 1174 currentFocused.getDrawingRect(mTempRect); 1175 offsetDescendantRectToMyCoords(currentFocused, mTempRect); 1176 int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); 1177 doScrollX(scrollDelta); 1178 } 1179 } 1180 1181 /** 1182 * Return true if child is an descendant of parent, (or equal to the parent). 1183 */ 1184 private boolean isViewDescendantOf(View child, View parent) { 1185 if (child == parent) { 1186 return true; 1187 } 1188 1189 final ViewParent theParent = child.getParent(); 1190 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 1191 } 1192 1193 /** 1194 * Fling the scroll view 1195 * 1196 * @param velocityX The initial velocity in the X direction. Positive 1197 * numbers mean that the finger/curor is moving down the screen, 1198 * which means we want to scroll towards the left. 1199 */ 1200 public void fling(int velocityX) { 1201 if (getChildCount() > 0) { 1202 int width = getWidth() - mPaddingRight - mPaddingLeft; 1203 int right = getChildAt(0).getWidth(); 1204 1205 mScroller.fling(mScrollX, mScrollY, velocityX, 0, 0, 1206 Math.max(0, right - width), 0, 0, width/2, 0); 1207 1208 final boolean movingRight = velocityX > 0; 1209 1210 View newFocused = findFocusableViewInMyBounds(movingRight, 1211 mScroller.getFinalX(), findFocus()); 1212 1213 if (newFocused == null) { 1214 newFocused = this; 1215 } 1216 1217 if (newFocused != findFocus() 1218 && newFocused.requestFocus(movingRight ? View.FOCUS_RIGHT : View.FOCUS_LEFT)) { 1219 mScrollViewMovedFocus = true; 1220 mScrollViewMovedFocus = false; 1221 } 1222 1223 awakenScrollBars(mScroller.getDuration()); 1224 invalidate(); 1225 } 1226 } 1227 1228 /** 1229 * {@inheritDoc} 1230 * 1231 * <p>This version also clamps the scrolling to the bounds of our child. 1232 */ 1233 public void scrollTo(int x, int y) { 1234 // we rely on the fact the View.scrollBy calls scrollTo. 1235 if (getChildCount() > 0) { 1236 View child = getChildAt(0); 1237 x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); 1238 y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); 1239 if (x != mScrollX || y != mScrollY) { 1240 super.scrollTo(x, y); 1241 } 1242 } 1243 } 1244 1245 private int clamp(int n, int my, int child) { 1246 if (my >= child || n < 0) { 1247 return 0; 1248 } 1249 if ((my + n) > child) { 1250 return child - my; 1251 } 1252 return n; 1253 } 1254} 1255