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