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