AbsListView.java revision 0211a0a10d20ec99bd78905ea9cd2960f7beb4c8
1/* 2 * Copyright (C) 2006 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 com.android.internal.R; 20 21import android.content.Context; 22import android.content.Intent; 23import android.content.res.Resources; 24import android.content.res.TypedArray; 25import android.graphics.Canvas; 26import android.graphics.Rect; 27import android.graphics.drawable.Drawable; 28import android.graphics.drawable.TransitionDrawable; 29import android.os.Debug; 30import android.os.Handler; 31import android.os.Parcel; 32import android.os.Parcelable; 33import android.os.StrictMode; 34import android.text.Editable; 35import android.text.TextUtils; 36import android.text.TextWatcher; 37import android.util.AttributeSet; 38import android.util.Log; 39import android.util.LongSparseArray; 40import android.util.SparseBooleanArray; 41import android.util.StateSet; 42import android.view.ActionMode; 43import android.view.ContextMenu.ContextMenuInfo; 44import android.view.Gravity; 45import android.view.HapticFeedbackConstants; 46import android.view.KeyEvent; 47import android.view.LayoutInflater; 48import android.view.Menu; 49import android.view.MenuItem; 50import android.view.MotionEvent; 51import android.view.VelocityTracker; 52import android.view.View; 53import android.view.ViewConfiguration; 54import android.view.ViewDebug; 55import android.view.ViewGroup; 56import android.view.ViewTreeObserver; 57import android.view.inputmethod.BaseInputConnection; 58import android.view.inputmethod.EditorInfo; 59import android.view.inputmethod.InputConnection; 60import android.view.inputmethod.InputConnectionWrapper; 61import android.view.inputmethod.InputMethodManager; 62 63import java.util.ArrayList; 64import java.util.List; 65 66/** 67 * Base class that can be used to implement virtualized lists of items. A list does 68 * not have a spatial definition here. For instance, subclases of this class can 69 * display the content of the list in a grid, in a carousel, as stack, etc. 70 * 71 * @attr ref android.R.styleable#AbsListView_listSelector 72 * @attr ref android.R.styleable#AbsListView_drawSelectorOnTop 73 * @attr ref android.R.styleable#AbsListView_stackFromBottom 74 * @attr ref android.R.styleable#AbsListView_scrollingCache 75 * @attr ref android.R.styleable#AbsListView_textFilterEnabled 76 * @attr ref android.R.styleable#AbsListView_transcriptMode 77 * @attr ref android.R.styleable#AbsListView_cacheColorHint 78 * @attr ref android.R.styleable#AbsListView_fastScrollEnabled 79 * @attr ref android.R.styleable#AbsListView_smoothScrollbar 80 * @attr ref android.R.styleable#AbsListView_choiceMode 81 */ 82public abstract class AbsListView extends AdapterView<ListAdapter> implements TextWatcher, 83 ViewTreeObserver.OnGlobalLayoutListener, Filter.FilterListener, 84 ViewTreeObserver.OnTouchModeChangeListener, 85 RemoteViewsAdapter.RemoteAdapterConnectionCallback { 86 87 /** 88 * Disables the transcript mode. 89 * 90 * @see #setTranscriptMode(int) 91 */ 92 public static final int TRANSCRIPT_MODE_DISABLED = 0; 93 /** 94 * The list will automatically scroll to the bottom when a data set change 95 * notification is received and only if the last item is already visible 96 * on screen. 97 * 98 * @see #setTranscriptMode(int) 99 */ 100 public static final int TRANSCRIPT_MODE_NORMAL = 1; 101 /** 102 * The list will automatically scroll to the bottom, no matter what items 103 * are currently visible. 104 * 105 * @see #setTranscriptMode(int) 106 */ 107 public static final int TRANSCRIPT_MODE_ALWAYS_SCROLL = 2; 108 109 /** 110 * Indicates that we are not in the middle of a touch gesture 111 */ 112 static final int TOUCH_MODE_REST = -1; 113 114 /** 115 * Indicates we just received the touch event and we are waiting to see if the it is a tap or a 116 * scroll gesture. 117 */ 118 static final int TOUCH_MODE_DOWN = 0; 119 120 /** 121 * Indicates the touch has been recognized as a tap and we are now waiting to see if the touch 122 * is a longpress 123 */ 124 static final int TOUCH_MODE_TAP = 1; 125 126 /** 127 * Indicates we have waited for everything we can wait for, but the user's finger is still down 128 */ 129 static final int TOUCH_MODE_DONE_WAITING = 2; 130 131 /** 132 * Indicates the touch gesture is a scroll 133 */ 134 static final int TOUCH_MODE_SCROLL = 3; 135 136 /** 137 * Indicates the view is in the process of being flung 138 */ 139 static final int TOUCH_MODE_FLING = 4; 140 141 /** 142 * Indicates the touch gesture is an overscroll - a scroll beyond the beginning or end. 143 */ 144 static final int TOUCH_MODE_OVERSCROLL = 5; 145 146 /** 147 * Indicates the view is being flung outside of normal content bounds 148 * and will spring back. 149 */ 150 static final int TOUCH_MODE_OVERFLING = 6; 151 152 /** 153 * Regular layout - usually an unsolicited layout from the view system 154 */ 155 static final int LAYOUT_NORMAL = 0; 156 157 /** 158 * Show the first item 159 */ 160 static final int LAYOUT_FORCE_TOP = 1; 161 162 /** 163 * Force the selected item to be on somewhere on the screen 164 */ 165 static final int LAYOUT_SET_SELECTION = 2; 166 167 /** 168 * Show the last item 169 */ 170 static final int LAYOUT_FORCE_BOTTOM = 3; 171 172 /** 173 * Make a mSelectedItem appear in a specific location and build the rest of 174 * the views from there. The top is specified by mSpecificTop. 175 */ 176 static final int LAYOUT_SPECIFIC = 4; 177 178 /** 179 * Layout to sync as a result of a data change. Restore mSyncPosition to have its top 180 * at mSpecificTop 181 */ 182 static final int LAYOUT_SYNC = 5; 183 184 /** 185 * Layout as a result of using the navigation keys 186 */ 187 static final int LAYOUT_MOVE_SELECTION = 6; 188 189 /** 190 * Normal list that does not indicate choices 191 */ 192 public static final int CHOICE_MODE_NONE = 0; 193 194 /** 195 * The list allows up to one choice 196 */ 197 public static final int CHOICE_MODE_SINGLE = 1; 198 199 /** 200 * The list allows multiple choices 201 */ 202 public static final int CHOICE_MODE_MULTIPLE = 2; 203 204 /** 205 * The list allows multiple choices in a modal selection mode 206 */ 207 public static final int CHOICE_MODE_MULTIPLE_MODAL = 3; 208 209 /** 210 * Controls if/how the user may choose/check items in the list 211 */ 212 int mChoiceMode = CHOICE_MODE_NONE; 213 214 /** 215 * Controls CHOICE_MODE_MULTIPLE_MODAL. null when inactive. 216 */ 217 ActionMode mChoiceActionMode; 218 219 /** 220 * Wrapper for the multiple choice mode callback; AbsListView needs to perform 221 * a few extra actions around what application code does. 222 */ 223 MultiChoiceModeWrapper mMultiChoiceModeCallback; 224 225 /** 226 * Running count of how many items are currently checked 227 */ 228 int mCheckedItemCount; 229 230 /** 231 * Running state of which positions are currently checked 232 */ 233 SparseBooleanArray mCheckStates; 234 235 /** 236 * Running state of which IDs are currently checked 237 */ 238 LongSparseArray<Boolean> mCheckedIdStates; 239 240 /** 241 * Controls how the next layout will happen 242 */ 243 int mLayoutMode = LAYOUT_NORMAL; 244 245 /** 246 * Should be used by subclasses to listen to changes in the dataset 247 */ 248 AdapterDataSetObserver mDataSetObserver; 249 250 /** 251 * The adapter containing the data to be displayed by this view 252 */ 253 ListAdapter mAdapter; 254 255 /** 256 * The remote adapter containing the data to be displayed by this view to be set 257 */ 258 private RemoteViewsAdapter mRemoteAdapter; 259 260 /** 261 * Indicates whether the list selector should be drawn on top of the children or behind 262 */ 263 boolean mDrawSelectorOnTop = false; 264 265 /** 266 * The drawable used to draw the selector 267 */ 268 Drawable mSelector; 269 270 /** 271 * Set to true if we would like to have the selector showing itself. 272 * We still need to draw and position it even if this is false. 273 */ 274 boolean mSelectorShowing; 275 276 /** 277 * The current position of the selector in the list. 278 */ 279 int mSelectorPosition = INVALID_POSITION; 280 281 /** 282 * Defines the selector's location and dimension at drawing time 283 */ 284 Rect mSelectorRect = new Rect(); 285 286 /** 287 * The data set used to store unused views that should be reused during the next layout 288 * to avoid creating new ones 289 */ 290 final RecycleBin mRecycler = new RecycleBin(); 291 292 /** 293 * The selection's left padding 294 */ 295 int mSelectionLeftPadding = 0; 296 297 /** 298 * The selection's top padding 299 */ 300 int mSelectionTopPadding = 0; 301 302 /** 303 * The selection's right padding 304 */ 305 int mSelectionRightPadding = 0; 306 307 /** 308 * The selection's bottom padding 309 */ 310 int mSelectionBottomPadding = 0; 311 312 /** 313 * This view's padding 314 */ 315 Rect mListPadding = new Rect(); 316 317 /** 318 * Subclasses must retain their measure spec from onMeasure() into this member 319 */ 320 int mWidthMeasureSpec = 0; 321 322 /** 323 * The top scroll indicator 324 */ 325 View mScrollUp; 326 327 /** 328 * The down scroll indicator 329 */ 330 View mScrollDown; 331 332 /** 333 * When the view is scrolling, this flag is set to true to indicate subclasses that 334 * the drawing cache was enabled on the children 335 */ 336 boolean mCachingStarted; 337 boolean mCachingActive; 338 339 /** 340 * The position of the view that received the down motion event 341 */ 342 int mMotionPosition; 343 344 /** 345 * The offset to the top of the mMotionPosition view when the down motion event was received 346 */ 347 int mMotionViewOriginalTop; 348 349 /** 350 * The desired offset to the top of the mMotionPosition view after a scroll 351 */ 352 int mMotionViewNewTop; 353 354 /** 355 * The X value associated with the the down motion event 356 */ 357 int mMotionX; 358 359 /** 360 * The Y value associated with the the down motion event 361 */ 362 int mMotionY; 363 364 /** 365 * One of TOUCH_MODE_REST, TOUCH_MODE_DOWN, TOUCH_MODE_TAP, TOUCH_MODE_SCROLL, or 366 * TOUCH_MODE_DONE_WAITING 367 */ 368 int mTouchMode = TOUCH_MODE_REST; 369 370 /** 371 * Y value from on the previous motion event (if any) 372 */ 373 int mLastY; 374 375 /** 376 * How far the finger moved before we started scrolling 377 */ 378 int mMotionCorrection; 379 380 /** 381 * Determines speed during touch scrolling 382 */ 383 private VelocityTracker mVelocityTracker; 384 385 /** 386 * Handles one frame of a fling 387 */ 388 private FlingRunnable mFlingRunnable; 389 390 /** 391 * Handles scrolling between positions within the list. 392 */ 393 private PositionScroller mPositionScroller; 394 395 /** 396 * The offset in pixels form the top of the AdapterView to the top 397 * of the currently selected view. Used to save and restore state. 398 */ 399 int mSelectedTop = 0; 400 401 /** 402 * Indicates whether the list is stacked from the bottom edge or 403 * the top edge. 404 */ 405 boolean mStackFromBottom; 406 407 /** 408 * When set to true, the list automatically discards the children's 409 * bitmap cache after scrolling. 410 */ 411 boolean mScrollingCacheEnabled; 412 413 /** 414 * Whether or not to enable the fast scroll feature on this list 415 */ 416 boolean mFastScrollEnabled; 417 418 /** 419 * Optional callback to notify client when scroll position has changed 420 */ 421 private OnScrollListener mOnScrollListener; 422 423 /** 424 * Keeps track of our accessory window 425 */ 426 PopupWindow mPopup; 427 428 /** 429 * Used with type filter window 430 */ 431 EditText mTextFilter; 432 433 /** 434 * Indicates whether to use pixels-based or position-based scrollbar 435 * properties. 436 */ 437 private boolean mSmoothScrollbarEnabled = true; 438 439 /** 440 * Indicates that this view supports filtering 441 */ 442 private boolean mTextFilterEnabled; 443 444 /** 445 * Indicates that this view is currently displaying a filtered view of the data 446 */ 447 private boolean mFiltered; 448 449 /** 450 * Rectangle used for hit testing children 451 */ 452 private Rect mTouchFrame; 453 454 /** 455 * The position to resurrect the selected position to. 456 */ 457 int mResurrectToPosition = INVALID_POSITION; 458 459 private ContextMenuInfo mContextMenuInfo = null; 460 461 /** 462 * Maximum distance to record overscroll 463 */ 464 int mOverscrollMax; 465 466 /** 467 * Content height divided by this is the overscroll limit. 468 */ 469 static final int OVERSCROLL_LIMIT_DIVISOR = 3; 470 471 /** 472 * Used to request a layout when we changed touch mode 473 */ 474 private static final int TOUCH_MODE_UNKNOWN = -1; 475 private static final int TOUCH_MODE_ON = 0; 476 private static final int TOUCH_MODE_OFF = 1; 477 478 private int mLastTouchMode = TOUCH_MODE_UNKNOWN; 479 480 private static final boolean PROFILE_SCROLLING = false; 481 private boolean mScrollProfilingStarted = false; 482 483 private static final boolean PROFILE_FLINGING = false; 484 private boolean mFlingProfilingStarted = false; 485 486 /** 487 * The StrictMode "critical time span" objects to catch animation 488 * stutters. Non-null when a time-sensitive animation is 489 * in-flight. Must call finish() on them when done animating. 490 * These are no-ops on user builds. 491 */ 492 private StrictMode.Span mScrollStrictSpan = null; 493 private StrictMode.Span mFlingStrictSpan = null; 494 495 /** 496 * The last CheckForLongPress runnable we posted, if any 497 */ 498 private CheckForLongPress mPendingCheckForLongPress; 499 500 /** 501 * The last CheckForTap runnable we posted, if any 502 */ 503 private Runnable mPendingCheckForTap; 504 505 /** 506 * The last CheckForKeyLongPress runnable we posted, if any 507 */ 508 private CheckForKeyLongPress mPendingCheckForKeyLongPress; 509 510 /** 511 * Acts upon click 512 */ 513 private AbsListView.PerformClick mPerformClick; 514 515 /** 516 * Delayed action for touch mode. 517 */ 518 private Runnable mTouchModeReset; 519 520 /** 521 * This view is in transcript mode -- it shows the bottom of the list when the data 522 * changes 523 */ 524 private int mTranscriptMode; 525 526 /** 527 * Indicates that this list is always drawn on top of a solid, single-color, opaque 528 * background 529 */ 530 private int mCacheColorHint; 531 532 /** 533 * The select child's view (from the adapter's getView) is enabled. 534 */ 535 private boolean mIsChildViewEnabled; 536 537 /** 538 * The last scroll state reported to clients through {@link OnScrollListener}. 539 */ 540 private int mLastScrollState = OnScrollListener.SCROLL_STATE_IDLE; 541 542 /** 543 * Helper object that renders and controls the fast scroll thumb. 544 */ 545 private FastScroller mFastScroller; 546 547 private boolean mGlobalLayoutListenerAddedFilter; 548 549 private int mTouchSlop; 550 private float mDensityScale; 551 552 private InputConnection mDefInputConnection; 553 private InputConnectionWrapper mPublicInputConnection; 554 555 private Runnable mClearScrollingCache; 556 private int mMinimumVelocity; 557 private int mMaximumVelocity; 558 private float mVelocityScale = 1.0f; 559 560 final boolean[] mIsScrap = new boolean[1]; 561 562 // True when the popup should be hidden because of a call to 563 // dispatchDisplayHint() 564 private boolean mPopupHidden; 565 566 /** 567 * ID of the active pointer. This is used to retain consistency during 568 * drags/flings if multiple pointers are used. 569 */ 570 private int mActivePointerId = INVALID_POINTER; 571 572 /** 573 * Sentinel value for no current active pointer. 574 * Used by {@link #mActivePointerId}. 575 */ 576 private static final int INVALID_POINTER = -1; 577 578 /** 579 * Maximum distance to overscroll by during edge effects 580 */ 581 int mOverscrollDistance; 582 583 /** 584 * Maximum distance to overfling during edge effects 585 */ 586 int mOverflingDistance; 587 588 // These two EdgeGlows are always set and used together. 589 // Checking one for null is as good as checking both. 590 591 /** 592 * Tracks the state of the top edge glow. 593 */ 594 private EdgeGlow mEdgeGlowTop; 595 596 /** 597 * Tracks the state of the bottom edge glow. 598 */ 599 private EdgeGlow mEdgeGlowBottom; 600 601 /** 602 * An estimate of how many pixels are between the top of the list and 603 * the top of the first position in the adapter, based on the last time 604 * we saw it. Used to hint where to draw edge glows. 605 */ 606 private int mFirstPositionDistanceGuess; 607 608 /** 609 * An estimate of how many pixels are between the bottom of the list and 610 * the bottom of the last position in the adapter, based on the last time 611 * we saw it. Used to hint where to draw edge glows. 612 */ 613 private int mLastPositionDistanceGuess; 614 615 /** 616 * Used for determining when to cancel out of overscroll. 617 */ 618 private int mDirection = 0; 619 620 /** 621 * Tracked on measurement in transcript mode. Makes sure that we can still pin to 622 * the bottom correctly on resizes. 623 */ 624 private boolean mForceTranscriptScroll; 625 626 /** 627 * Interface definition for a callback to be invoked when the list or grid 628 * has been scrolled. 629 */ 630 public interface OnScrollListener { 631 632 /** 633 * The view is not scrolling. Note navigating the list using the trackball counts as 634 * being in the idle state since these transitions are not animated. 635 */ 636 public static int SCROLL_STATE_IDLE = 0; 637 638 /** 639 * The user is scrolling using touch, and their finger is still on the screen 640 */ 641 public static int SCROLL_STATE_TOUCH_SCROLL = 1; 642 643 /** 644 * The user had previously been scrolling using touch and had performed a fling. The 645 * animation is now coasting to a stop 646 */ 647 public static int SCROLL_STATE_FLING = 2; 648 649 /** 650 * Callback method to be invoked while the list view or grid view is being scrolled. If the 651 * view is being scrolled, this method will be called before the next frame of the scroll is 652 * rendered. In particular, it will be called before any calls to 653 * {@link Adapter#getView(int, View, ViewGroup)}. 654 * 655 * @param view The view whose scroll state is being reported 656 * 657 * @param scrollState The current scroll state. One of {@link #SCROLL_STATE_IDLE}, 658 * {@link #SCROLL_STATE_TOUCH_SCROLL} or {@link #SCROLL_STATE_IDLE}. 659 */ 660 public void onScrollStateChanged(AbsListView view, int scrollState); 661 662 /** 663 * Callback method to be invoked when the list or grid has been scrolled. This will be 664 * called after the scroll has completed 665 * @param view The view whose scroll state is being reported 666 * @param firstVisibleItem the index of the first visible cell (ignore if 667 * visibleItemCount == 0) 668 * @param visibleItemCount the number of visible cells 669 * @param totalItemCount the number of items in the list adaptor 670 */ 671 public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, 672 int totalItemCount); 673 } 674 675 /** 676 * The top-level view of a list item can implement this interface to allow 677 * itself to modify the bounds of the selection shown for that item. 678 */ 679 public interface SelectionBoundsAdjuster { 680 /** 681 * Called to allow the list item to adjust the bounds shown for 682 * its selection. 683 * 684 * @param bounds On call, this contains the bounds the list has 685 * selected for the item (that is the bounds of the entire view). The 686 * values can be modified as desired. 687 */ 688 public void adjustListItemSelectionBounds(Rect bounds); 689 } 690 691 public AbsListView(Context context) { 692 super(context); 693 initAbsListView(); 694 695 setVerticalScrollBarEnabled(true); 696 TypedArray a = context.obtainStyledAttributes(R.styleable.View); 697 initializeScrollbars(a); 698 a.recycle(); 699 } 700 701 public AbsListView(Context context, AttributeSet attrs) { 702 this(context, attrs, com.android.internal.R.attr.absListViewStyle); 703 } 704 705 public AbsListView(Context context, AttributeSet attrs, int defStyle) { 706 super(context, attrs, defStyle); 707 initAbsListView(); 708 709 TypedArray a = context.obtainStyledAttributes(attrs, 710 com.android.internal.R.styleable.AbsListView, defStyle, 0); 711 712 Drawable d = a.getDrawable(com.android.internal.R.styleable.AbsListView_listSelector); 713 if (d != null) { 714 setSelector(d); 715 } 716 717 mDrawSelectorOnTop = a.getBoolean( 718 com.android.internal.R.styleable.AbsListView_drawSelectorOnTop, false); 719 720 boolean stackFromBottom = a.getBoolean(R.styleable.AbsListView_stackFromBottom, false); 721 setStackFromBottom(stackFromBottom); 722 723 boolean scrollingCacheEnabled = a.getBoolean(R.styleable.AbsListView_scrollingCache, true); 724 setScrollingCacheEnabled(scrollingCacheEnabled); 725 726 boolean useTextFilter = a.getBoolean(R.styleable.AbsListView_textFilterEnabled, false); 727 setTextFilterEnabled(useTextFilter); 728 729 int transcriptMode = a.getInt(R.styleable.AbsListView_transcriptMode, 730 TRANSCRIPT_MODE_DISABLED); 731 setTranscriptMode(transcriptMode); 732 733 int color = a.getColor(R.styleable.AbsListView_cacheColorHint, 0); 734 setCacheColorHint(color); 735 736 boolean enableFastScroll = a.getBoolean(R.styleable.AbsListView_fastScrollEnabled, false); 737 setFastScrollEnabled(enableFastScroll); 738 739 boolean smoothScrollbar = a.getBoolean(R.styleable.AbsListView_smoothScrollbar, true); 740 setSmoothScrollbarEnabled(smoothScrollbar); 741 742 setChoiceMode(a.getInt(R.styleable.AbsListView_choiceMode, CHOICE_MODE_NONE)); 743 setFastScrollAlwaysVisible( 744 a.getBoolean(R.styleable.AbsListView_fastScrollAlwaysVisible, false)); 745 746 a.recycle(); 747 } 748 749 private void initAbsListView() { 750 // Setting focusable in touch mode will set the focusable property to true 751 setClickable(true); 752 setFocusableInTouchMode(true); 753 setWillNotDraw(false); 754 setAlwaysDrawnWithCacheEnabled(false); 755 setScrollingCacheEnabled(true); 756 757 final ViewConfiguration configuration = ViewConfiguration.get(mContext); 758 mTouchSlop = configuration.getScaledTouchSlop(); 759 mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); 760 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 761 mOverscrollDistance = configuration.getScaledOverscrollDistance(); 762 mOverflingDistance = configuration.getScaledOverflingDistance(); 763 764 mDensityScale = getContext().getResources().getDisplayMetrics().density; 765 } 766 767 @Override 768 public void setOverScrollMode(int mode) { 769 if (mode != OVER_SCROLL_NEVER) { 770 if (mEdgeGlowTop == null) { 771 Context context = getContext(); 772 final Resources res = context.getResources(); 773 final Drawable edge = res.getDrawable(R.drawable.overscroll_edge); 774 final Drawable glow = res.getDrawable(R.drawable.overscroll_glow); 775 mEdgeGlowTop = new EdgeGlow(context, edge, glow); 776 mEdgeGlowBottom = new EdgeGlow(context, edge, glow); 777 } 778 } else { 779 mEdgeGlowTop = null; 780 mEdgeGlowBottom = null; 781 } 782 super.setOverScrollMode(mode); 783 } 784 785 /** 786 * {@inheritDoc} 787 */ 788 @Override 789 public void setAdapter(ListAdapter adapter) { 790 if (adapter != null) { 791 if (mChoiceMode != CHOICE_MODE_NONE && mAdapter.hasStableIds() && 792 mCheckedIdStates == null) { 793 mCheckedIdStates = new LongSparseArray<Boolean>(); 794 } 795 } 796 797 if (mCheckStates != null) { 798 mCheckStates.clear(); 799 } 800 801 if (mCheckedIdStates != null) { 802 mCheckedIdStates.clear(); 803 } 804 } 805 806 /** 807 * Returns the number of items currently selected. This will only be valid 808 * if the choice mode is not {@link #CHOICE_MODE_NONE} (default). 809 * 810 * <p>To determine the specific items that are currently selected, use one of 811 * the <code>getChecked*</code> methods. 812 * 813 * @return The number of items currently selected 814 * 815 * @see #getCheckedItemPosition() 816 * @see #getCheckedItemPositions() 817 * @see #getCheckedItemIds() 818 */ 819 public int getCheckedItemCount() { 820 return mCheckedItemCount; 821 } 822 823 /** 824 * Returns the checked state of the specified position. The result is only 825 * valid if the choice mode has been set to {@link #CHOICE_MODE_SINGLE} 826 * or {@link #CHOICE_MODE_MULTIPLE}. 827 * 828 * @param position The item whose checked state to return 829 * @return The item's checked state or <code>false</code> if choice mode 830 * is invalid 831 * 832 * @see #setChoiceMode(int) 833 */ 834 public boolean isItemChecked(int position) { 835 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) { 836 return mCheckStates.get(position); 837 } 838 839 return false; 840 } 841 842 /** 843 * Returns the currently checked item. The result is only valid if the choice 844 * mode has been set to {@link #CHOICE_MODE_SINGLE}. 845 * 846 * @return The position of the currently checked item or 847 * {@link #INVALID_POSITION} if nothing is selected 848 * 849 * @see #setChoiceMode(int) 850 */ 851 public int getCheckedItemPosition() { 852 if (mChoiceMode == CHOICE_MODE_SINGLE && mCheckStates != null && mCheckStates.size() == 1) { 853 return mCheckStates.keyAt(0); 854 } 855 856 return INVALID_POSITION; 857 } 858 859 /** 860 * Returns the set of checked items in the list. The result is only valid if 861 * the choice mode has not been set to {@link #CHOICE_MODE_NONE}. 862 * 863 * @return A SparseBooleanArray which will return true for each call to 864 * get(int position) where position is a position in the list, 865 * or <code>null</code> if the choice mode is set to 866 * {@link #CHOICE_MODE_NONE}. 867 */ 868 public SparseBooleanArray getCheckedItemPositions() { 869 if (mChoiceMode != CHOICE_MODE_NONE) { 870 return mCheckStates; 871 } 872 return null; 873 } 874 875 /** 876 * Returns the set of checked items ids. The result is only valid if the 877 * choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter 878 * has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true}) 879 * 880 * @return A new array which contains the id of each checked item in the 881 * list. 882 */ 883 public long[] getCheckedItemIds() { 884 if (mChoiceMode == CHOICE_MODE_NONE || mCheckedIdStates == null || mAdapter == null) { 885 return new long[0]; 886 } 887 888 final LongSparseArray<Boolean> idStates = mCheckedIdStates; 889 final int count = idStates.size(); 890 final long[] ids = new long[count]; 891 892 for (int i = 0; i < count; i++) { 893 ids[i] = idStates.keyAt(i); 894 } 895 896 return ids; 897 } 898 899 /** 900 * Clear any choices previously set 901 */ 902 public void clearChoices() { 903 if (mCheckStates != null) { 904 mCheckStates.clear(); 905 } 906 if (mCheckedIdStates != null) { 907 mCheckedIdStates.clear(); 908 } 909 mCheckedItemCount = 0; 910 } 911 912 /** 913 * Sets the checked state of the specified position. The is only valid if 914 * the choice mode has been set to {@link #CHOICE_MODE_SINGLE} or 915 * {@link #CHOICE_MODE_MULTIPLE}. 916 * 917 * @param position The item whose checked state is to be checked 918 * @param value The new checked state for the item 919 */ 920 public void setItemChecked(int position, boolean value) { 921 if (mChoiceMode == CHOICE_MODE_NONE) { 922 return; 923 } 924 925 // Start selection mode if needed. We don't need to if we're unchecking something. 926 if (value && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode == null) { 927 mChoiceActionMode = startActionMode(mMultiChoiceModeCallback); 928 } 929 930 if (mChoiceMode == CHOICE_MODE_MULTIPLE || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) { 931 boolean oldValue = mCheckStates.get(position); 932 mCheckStates.put(position, value); 933 if (mCheckedIdStates != null && mAdapter.hasStableIds()) { 934 if (value) { 935 mCheckedIdStates.put(mAdapter.getItemId(position), Boolean.TRUE); 936 } else { 937 mCheckedIdStates.delete(mAdapter.getItemId(position)); 938 } 939 } 940 if (oldValue != value) { 941 if (value) { 942 mCheckedItemCount++; 943 } else { 944 mCheckedItemCount--; 945 } 946 } 947 if (mChoiceActionMode != null) { 948 final long id = mAdapter.getItemId(position); 949 mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode, 950 position, id, value); 951 } 952 } else { 953 boolean updateIds = mCheckedIdStates != null && mAdapter.hasStableIds(); 954 // Clear all values if we're checking something, or unchecking the currently 955 // selected item 956 if (value || isItemChecked(position)) { 957 mCheckStates.clear(); 958 if (updateIds) { 959 mCheckedIdStates.clear(); 960 } 961 } 962 // this may end up selecting the value we just cleared but this way 963 // we ensure length of mCheckStates is 1, a fact getCheckedItemPosition relies on 964 if (value) { 965 mCheckStates.put(position, true); 966 if (updateIds) { 967 mCheckedIdStates.put(mAdapter.getItemId(position), Boolean.TRUE); 968 } 969 mCheckedItemCount = 1; 970 } else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) { 971 mCheckedItemCount = 0; 972 } 973 } 974 975 // Do not generate a data change while we are in the layout phase 976 if (!mInLayout && !mBlockLayoutRequests) { 977 mDataChanged = true; 978 rememberSyncState(); 979 requestLayout(); 980 } 981 } 982 983 @Override 984 public boolean performItemClick(View view, int position, long id) { 985 boolean handled = false; 986 boolean dispatchItemClick = true; 987 988 if (mChoiceMode != CHOICE_MODE_NONE) { 989 handled = true; 990 991 if (mChoiceMode == CHOICE_MODE_MULTIPLE || 992 (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode != null)) { 993 boolean newValue = !mCheckStates.get(position, false); 994 mCheckStates.put(position, newValue); 995 if (mCheckedIdStates != null && mAdapter.hasStableIds()) { 996 if (newValue) { 997 mCheckedIdStates.put(mAdapter.getItemId(position), Boolean.TRUE); 998 } else { 999 mCheckedIdStates.delete(mAdapter.getItemId(position)); 1000 } 1001 } 1002 if (newValue) { 1003 mCheckedItemCount++; 1004 } else { 1005 mCheckedItemCount--; 1006 } 1007 if (mChoiceActionMode != null) { 1008 mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode, 1009 position, id, newValue); 1010 dispatchItemClick = false; 1011 } 1012 } else if (mChoiceMode == CHOICE_MODE_SINGLE) { 1013 boolean newValue = !mCheckStates.get(position, false); 1014 if (newValue) { 1015 mCheckStates.clear(); 1016 mCheckStates.put(position, true); 1017 if (mCheckedIdStates != null && mAdapter.hasStableIds()) { 1018 mCheckedIdStates.clear(); 1019 mCheckedIdStates.put(mAdapter.getItemId(position), Boolean.TRUE); 1020 } 1021 mCheckedItemCount = 1; 1022 } else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) { 1023 mCheckedItemCount = 0; 1024 } 1025 } 1026 1027 mDataChanged = true; 1028 rememberSyncState(); 1029 requestLayout(); 1030 } 1031 1032 if (dispatchItemClick) { 1033 handled |= super.performItemClick(view, position, id); 1034 } 1035 1036 return handled; 1037 } 1038 1039 /** 1040 * @see #setChoiceMode(int) 1041 * 1042 * @return The current choice mode 1043 */ 1044 public int getChoiceMode() { 1045 return mChoiceMode; 1046 } 1047 1048 /** 1049 * Defines the choice behavior for the List. By default, Lists do not have any choice behavior 1050 * ({@link #CHOICE_MODE_NONE}). By setting the choiceMode to {@link #CHOICE_MODE_SINGLE}, the 1051 * List allows up to one item to be in a chosen state. By setting the choiceMode to 1052 * {@link #CHOICE_MODE_MULTIPLE}, the list allows any number of items to be chosen. 1053 * 1054 * @param choiceMode One of {@link #CHOICE_MODE_NONE}, {@link #CHOICE_MODE_SINGLE}, or 1055 * {@link #CHOICE_MODE_MULTIPLE} 1056 */ 1057 public void setChoiceMode(int choiceMode) { 1058 mChoiceMode = choiceMode; 1059 if (mChoiceActionMode != null) { 1060 mChoiceActionMode.finish(); 1061 mChoiceActionMode = null; 1062 } 1063 if (mChoiceMode != CHOICE_MODE_NONE) { 1064 if (mCheckStates == null) { 1065 mCheckStates = new SparseBooleanArray(); 1066 } 1067 if (mCheckedIdStates == null && mAdapter != null && mAdapter.hasStableIds()) { 1068 mCheckedIdStates = new LongSparseArray<Boolean>(); 1069 } 1070 // Modal multi-choice mode only has choices when the mode is active. Clear them. 1071 if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) { 1072 clearChoices(); 1073 setLongClickable(true); 1074 } 1075 } 1076 } 1077 1078 /** 1079 * Set a {@link MultiChoiceModeListener} that will manage the lifecycle of the 1080 * selection {@link ActionMode}. Only used when the choice mode is set to 1081 * {@link #CHOICE_MODE_MULTIPLE_MODAL}. 1082 * 1083 * @param listener Listener that will manage the selection mode 1084 * 1085 * @see #setChoiceMode(int) 1086 */ 1087 public void setMultiChoiceModeListener(MultiChoiceModeListener listener) { 1088 if (mMultiChoiceModeCallback == null) { 1089 mMultiChoiceModeCallback = new MultiChoiceModeWrapper(); 1090 } 1091 mMultiChoiceModeCallback.setWrapped(listener); 1092 } 1093 1094 /** 1095 * @return true if all list content currently fits within the view boundaries 1096 */ 1097 private boolean contentFits() { 1098 final int childCount = getChildCount(); 1099 if (childCount == 0) return true; 1100 if (childCount != mItemCount) return false; 1101 1102 return getChildAt(0).getTop() >= mListPadding.top && 1103 getChildAt(childCount - 1).getBottom() <= getHeight() - mListPadding.bottom; 1104 } 1105 1106 /** 1107 * Enables fast scrolling by letting the user quickly scroll through lists by 1108 * dragging the fast scroll thumb. The adapter attached to the list may want 1109 * to implement {@link SectionIndexer} if it wishes to display alphabet preview and 1110 * jump between sections of the list. 1111 * @see SectionIndexer 1112 * @see #isFastScrollEnabled() 1113 * @param enabled whether or not to enable fast scrolling 1114 */ 1115 public void setFastScrollEnabled(boolean enabled) { 1116 mFastScrollEnabled = enabled; 1117 if (enabled) { 1118 if (mFastScroller == null) { 1119 mFastScroller = new FastScroller(getContext(), this); 1120 } 1121 } else { 1122 if (mFastScroller != null) { 1123 mFastScroller.stop(); 1124 mFastScroller = null; 1125 } 1126 } 1127 } 1128 1129 /** 1130 * Set whether or not the fast scroller should always be shown in place of the 1131 * standard scrollbars. Fast scrollers shown in this way will not fade out and will 1132 * be a permanent fixture within the list. Best combined with an inset scroll bar style 1133 * that will ensure enough padding. This will enable fast scrolling if it is not 1134 * already enabled. 1135 * 1136 * @param alwaysShow true if the fast scroller should always be displayed. 1137 * @see #setScrollBarStyle(int) 1138 * @see #setFastScrollEnabled(boolean) 1139 */ 1140 public void setFastScrollAlwaysVisible(boolean alwaysShow) { 1141 if (alwaysShow && !mFastScrollEnabled) { 1142 setFastScrollEnabled(true); 1143 } 1144 1145 if (mFastScroller != null) { 1146 mFastScroller.setAlwaysShow(alwaysShow); 1147 } 1148 1149 computeOpaqueFlags(); 1150 recomputePadding(); 1151 } 1152 1153 /** 1154 * Returns true if the fast scroller is set to always show on this view rather than 1155 * fade out when not in use. 1156 * 1157 * @return true if the fast scroller will always show. 1158 * @see #setFastScrollAlwaysVisible(boolean) 1159 */ 1160 public boolean isFastScrollAlwaysVisible() { 1161 return mFastScrollEnabled && mFastScroller.isAlwaysShowEnabled(); 1162 } 1163 1164 @Override 1165 public int getVerticalScrollbarWidth() { 1166 if (isFastScrollAlwaysVisible()) { 1167 return Math.max(super.getVerticalScrollbarWidth(), mFastScroller.getWidth()); 1168 } 1169 return super.getVerticalScrollbarWidth(); 1170 } 1171 1172 /** 1173 * Returns the current state of the fast scroll feature. 1174 * @see #setFastScrollEnabled(boolean) 1175 * @return true if fast scroll is enabled, false otherwise 1176 */ 1177 @ViewDebug.ExportedProperty 1178 public boolean isFastScrollEnabled() { 1179 return mFastScrollEnabled; 1180 } 1181 1182 @Override 1183 public void setVerticalScrollbarPosition(int position) { 1184 super.setVerticalScrollbarPosition(position); 1185 if (mFastScroller != null) { 1186 mFastScroller.setScrollbarPosition(position); 1187 } 1188 } 1189 1190 /** 1191 * If fast scroll is visible, then don't draw the vertical scrollbar. 1192 * @hide 1193 */ 1194 @Override 1195 protected boolean isVerticalScrollBarHidden() { 1196 return mFastScroller != null && mFastScroller.isVisible(); 1197 } 1198 1199 /** 1200 * When smooth scrollbar is enabled, the position and size of the scrollbar thumb 1201 * is computed based on the number of visible pixels in the visible items. This 1202 * however assumes that all list items have the same height. If you use a list in 1203 * which items have different heights, the scrollbar will change appearance as the 1204 * user scrolls through the list. To avoid this issue, you need to disable this 1205 * property. 1206 * 1207 * When smooth scrollbar is disabled, the position and size of the scrollbar thumb 1208 * is based solely on the number of items in the adapter and the position of the 1209 * visible items inside the adapter. This provides a stable scrollbar as the user 1210 * navigates through a list of items with varying heights. 1211 * 1212 * @param enabled Whether or not to enable smooth scrollbar. 1213 * 1214 * @see #setSmoothScrollbarEnabled(boolean) 1215 * @attr ref android.R.styleable#AbsListView_smoothScrollbar 1216 */ 1217 public void setSmoothScrollbarEnabled(boolean enabled) { 1218 mSmoothScrollbarEnabled = enabled; 1219 } 1220 1221 /** 1222 * Returns the current state of the fast scroll feature. 1223 * 1224 * @return True if smooth scrollbar is enabled is enabled, false otherwise. 1225 * 1226 * @see #setSmoothScrollbarEnabled(boolean) 1227 */ 1228 @ViewDebug.ExportedProperty 1229 public boolean isSmoothScrollbarEnabled() { 1230 return mSmoothScrollbarEnabled; 1231 } 1232 1233 /** 1234 * Set the listener that will receive notifications every time the list scrolls. 1235 * 1236 * @param l the scroll listener 1237 */ 1238 public void setOnScrollListener(OnScrollListener l) { 1239 mOnScrollListener = l; 1240 invokeOnItemScrollListener(); 1241 } 1242 1243 /** 1244 * Notify our scroll listener (if there is one) of a change in scroll state 1245 */ 1246 void invokeOnItemScrollListener() { 1247 if (mFastScroller != null) { 1248 mFastScroller.onScroll(this, mFirstPosition, getChildCount(), mItemCount); 1249 } 1250 if (mOnScrollListener != null) { 1251 mOnScrollListener.onScroll(this, mFirstPosition, getChildCount(), mItemCount); 1252 } 1253 } 1254 1255 /** 1256 * Indicates whether the children's drawing cache is used during a scroll. 1257 * By default, the drawing cache is enabled but this will consume more memory. 1258 * 1259 * @return true if the scrolling cache is enabled, false otherwise 1260 * 1261 * @see #setScrollingCacheEnabled(boolean) 1262 * @see View#setDrawingCacheEnabled(boolean) 1263 */ 1264 @ViewDebug.ExportedProperty 1265 public boolean isScrollingCacheEnabled() { 1266 return mScrollingCacheEnabled; 1267 } 1268 1269 /** 1270 * Enables or disables the children's drawing cache during a scroll. 1271 * By default, the drawing cache is enabled but this will use more memory. 1272 * 1273 * When the scrolling cache is enabled, the caches are kept after the 1274 * first scrolling. You can manually clear the cache by calling 1275 * {@link android.view.ViewGroup#setChildrenDrawingCacheEnabled(boolean)}. 1276 * 1277 * @param enabled true to enable the scroll cache, false otherwise 1278 * 1279 * @see #isScrollingCacheEnabled() 1280 * @see View#setDrawingCacheEnabled(boolean) 1281 */ 1282 public void setScrollingCacheEnabled(boolean enabled) { 1283 if (mScrollingCacheEnabled && !enabled) { 1284 clearScrollingCache(); 1285 } 1286 mScrollingCacheEnabled = enabled; 1287 } 1288 1289 /** 1290 * Enables or disables the type filter window. If enabled, typing when 1291 * this view has focus will filter the children to match the users input. 1292 * Note that the {@link Adapter} used by this view must implement the 1293 * {@link Filterable} interface. 1294 * 1295 * @param textFilterEnabled true to enable type filtering, false otherwise 1296 * 1297 * @see Filterable 1298 */ 1299 public void setTextFilterEnabled(boolean textFilterEnabled) { 1300 mTextFilterEnabled = textFilterEnabled; 1301 } 1302 1303 /** 1304 * Indicates whether type filtering is enabled for this view 1305 * 1306 * @return true if type filtering is enabled, false otherwise 1307 * 1308 * @see #setTextFilterEnabled(boolean) 1309 * @see Filterable 1310 */ 1311 @ViewDebug.ExportedProperty 1312 public boolean isTextFilterEnabled() { 1313 return mTextFilterEnabled; 1314 } 1315 1316 @Override 1317 public void getFocusedRect(Rect r) { 1318 View view = getSelectedView(); 1319 if (view != null && view.getParent() == this) { 1320 // the focused rectangle of the selected view offset into the 1321 // coordinate space of this view. 1322 view.getFocusedRect(r); 1323 offsetDescendantRectToMyCoords(view, r); 1324 } else { 1325 // otherwise, just the norm 1326 super.getFocusedRect(r); 1327 } 1328 } 1329 1330 private void useDefaultSelector() { 1331 setSelector(getResources().getDrawable( 1332 com.android.internal.R.drawable.list_selector_background)); 1333 } 1334 1335 /** 1336 * Indicates whether the content of this view is pinned to, or stacked from, 1337 * the bottom edge. 1338 * 1339 * @return true if the content is stacked from the bottom edge, false otherwise 1340 */ 1341 @ViewDebug.ExportedProperty 1342 public boolean isStackFromBottom() { 1343 return mStackFromBottom; 1344 } 1345 1346 /** 1347 * When stack from bottom is set to true, the list fills its content starting from 1348 * the bottom of the view. 1349 * 1350 * @param stackFromBottom true to pin the view's content to the bottom edge, 1351 * false to pin the view's content to the top edge 1352 */ 1353 public void setStackFromBottom(boolean stackFromBottom) { 1354 if (mStackFromBottom != stackFromBottom) { 1355 mStackFromBottom = stackFromBottom; 1356 requestLayoutIfNecessary(); 1357 } 1358 } 1359 1360 void requestLayoutIfNecessary() { 1361 if (getChildCount() > 0) { 1362 resetList(); 1363 requestLayout(); 1364 invalidate(); 1365 } 1366 } 1367 1368 static class SavedState extends BaseSavedState { 1369 long selectedId; 1370 long firstId; 1371 int viewTop; 1372 int position; 1373 int height; 1374 String filter; 1375 boolean inActionMode; 1376 int checkedItemCount; 1377 SparseBooleanArray checkState; 1378 LongSparseArray<Boolean> checkIdState; 1379 1380 /** 1381 * Constructor called from {@link AbsListView#onSaveInstanceState()} 1382 */ 1383 SavedState(Parcelable superState) { 1384 super(superState); 1385 } 1386 1387 /** 1388 * Constructor called from {@link #CREATOR} 1389 */ 1390 private SavedState(Parcel in) { 1391 super(in); 1392 selectedId = in.readLong(); 1393 firstId = in.readLong(); 1394 viewTop = in.readInt(); 1395 position = in.readInt(); 1396 height = in.readInt(); 1397 filter = in.readString(); 1398 inActionMode = in.readByte() != 0; 1399 checkedItemCount = in.readInt(); 1400 checkState = in.readSparseBooleanArray(); 1401 long[] idState = in.createLongArray(); 1402 1403 if (idState.length > 0) { 1404 checkIdState = new LongSparseArray<Boolean>(); 1405 checkIdState.setValues(idState, Boolean.TRUE); 1406 } 1407 } 1408 1409 @Override 1410 public void writeToParcel(Parcel out, int flags) { 1411 super.writeToParcel(out, flags); 1412 out.writeLong(selectedId); 1413 out.writeLong(firstId); 1414 out.writeInt(viewTop); 1415 out.writeInt(position); 1416 out.writeInt(height); 1417 out.writeString(filter); 1418 out.writeByte((byte) (inActionMode ? 1 : 0)); 1419 out.writeInt(checkedItemCount); 1420 out.writeSparseBooleanArray(checkState); 1421 out.writeLongArray(checkIdState != null ? checkIdState.getKeys() : new long[0]); 1422 } 1423 1424 @Override 1425 public String toString() { 1426 return "AbsListView.SavedState{" 1427 + Integer.toHexString(System.identityHashCode(this)) 1428 + " selectedId=" + selectedId 1429 + " firstId=" + firstId 1430 + " viewTop=" + viewTop 1431 + " position=" + position 1432 + " height=" + height 1433 + " filter=" + filter 1434 + " checkState=" + checkState + "}"; 1435 } 1436 1437 public static final Parcelable.Creator<SavedState> CREATOR 1438 = new Parcelable.Creator<SavedState>() { 1439 public SavedState createFromParcel(Parcel in) { 1440 return new SavedState(in); 1441 } 1442 1443 public SavedState[] newArray(int size) { 1444 return new SavedState[size]; 1445 } 1446 }; 1447 } 1448 1449 @Override 1450 public Parcelable onSaveInstanceState() { 1451 /* 1452 * This doesn't really make sense as the place to dismiss the 1453 * popups, but there don't seem to be any other useful hooks 1454 * that happen early enough to keep from getting complaints 1455 * about having leaked the window. 1456 */ 1457 dismissPopup(); 1458 1459 Parcelable superState = super.onSaveInstanceState(); 1460 1461 SavedState ss = new SavedState(superState); 1462 1463 boolean haveChildren = getChildCount() > 0 && mItemCount > 0; 1464 long selectedId = getSelectedItemId(); 1465 ss.selectedId = selectedId; 1466 ss.height = getHeight(); 1467 1468 if (selectedId >= 0) { 1469 // Remember the selection 1470 ss.viewTop = mSelectedTop; 1471 ss.position = getSelectedItemPosition(); 1472 ss.firstId = INVALID_POSITION; 1473 } else { 1474 if (haveChildren && mFirstPosition > 0) { 1475 // Remember the position of the first child. 1476 // We only do this if we are not currently at the top of 1477 // the list, for two reasons: 1478 // (1) The list may be in the process of becoming empty, in 1479 // which case mItemCount may not be 0, but if we try to 1480 // ask for any information about position 0 we will crash. 1481 // (2) Being "at the top" seems like a special case, anyway, 1482 // and the user wouldn't expect to end up somewhere else when 1483 // they revisit the list even if its content has changed. 1484 View v = getChildAt(0); 1485 ss.viewTop = v.getTop(); 1486 int firstPos = mFirstPosition; 1487 if (firstPos >= mItemCount) { 1488 firstPos = mItemCount - 1; 1489 } 1490 ss.position = firstPos; 1491 ss.firstId = mAdapter.getItemId(firstPos); 1492 } else { 1493 ss.viewTop = 0; 1494 ss.firstId = INVALID_POSITION; 1495 ss.position = 0; 1496 } 1497 } 1498 1499 ss.filter = null; 1500 if (mFiltered) { 1501 final EditText textFilter = mTextFilter; 1502 if (textFilter != null) { 1503 Editable filterText = textFilter.getText(); 1504 if (filterText != null) { 1505 ss.filter = filterText.toString(); 1506 } 1507 } 1508 } 1509 1510 ss.inActionMode = mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode != null; 1511 1512 ss.checkState = mCheckStates; 1513 ss.checkIdState = mCheckedIdStates; 1514 ss.checkedItemCount = mCheckedItemCount; 1515 1516 return ss; 1517 } 1518 1519 @Override 1520 public void onRestoreInstanceState(Parcelable state) { 1521 SavedState ss = (SavedState) state; 1522 1523 super.onRestoreInstanceState(ss.getSuperState()); 1524 mDataChanged = true; 1525 1526 mSyncHeight = ss.height; 1527 1528 if (ss.selectedId >= 0) { 1529 mNeedSync = true; 1530 mSyncRowId = ss.selectedId; 1531 mSyncPosition = ss.position; 1532 mSpecificTop = ss.viewTop; 1533 mSyncMode = SYNC_SELECTED_POSITION; 1534 } else if (ss.firstId >= 0) { 1535 setSelectedPositionInt(INVALID_POSITION); 1536 // Do this before setting mNeedSync since setNextSelectedPosition looks at mNeedSync 1537 setNextSelectedPositionInt(INVALID_POSITION); 1538 mSelectorPosition = INVALID_POSITION; 1539 mNeedSync = true; 1540 mSyncRowId = ss.firstId; 1541 mSyncPosition = ss.position; 1542 mSpecificTop = ss.viewTop; 1543 mSyncMode = SYNC_FIRST_POSITION; 1544 } 1545 1546 setFilterText(ss.filter); 1547 1548 if (ss.checkState != null) { 1549 mCheckStates = ss.checkState; 1550 } 1551 1552 if (ss.checkIdState != null) { 1553 mCheckedIdStates = ss.checkIdState; 1554 } 1555 1556 mCheckedItemCount = ss.checkedItemCount; 1557 1558 if (ss.inActionMode && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && 1559 mMultiChoiceModeCallback != null) { 1560 mChoiceActionMode = startActionMode(mMultiChoiceModeCallback); 1561 } 1562 1563 requestLayout(); 1564 } 1565 1566 private boolean acceptFilter() { 1567 return mTextFilterEnabled && getAdapter() instanceof Filterable && 1568 ((Filterable) getAdapter()).getFilter() != null; 1569 } 1570 1571 /** 1572 * Sets the initial value for the text filter. 1573 * @param filterText The text to use for the filter. 1574 * 1575 * @see #setTextFilterEnabled 1576 */ 1577 public void setFilterText(String filterText) { 1578 // TODO: Should we check for acceptFilter()? 1579 if (mTextFilterEnabled && !TextUtils.isEmpty(filterText)) { 1580 createTextFilter(false); 1581 // This is going to call our listener onTextChanged, but we might not 1582 // be ready to bring up a window yet 1583 mTextFilter.setText(filterText); 1584 mTextFilter.setSelection(filterText.length()); 1585 if (mAdapter instanceof Filterable) { 1586 // if mPopup is non-null, then onTextChanged will do the filtering 1587 if (mPopup == null) { 1588 Filter f = ((Filterable) mAdapter).getFilter(); 1589 f.filter(filterText); 1590 } 1591 // Set filtered to true so we will display the filter window when our main 1592 // window is ready 1593 mFiltered = true; 1594 mDataSetObserver.clearSavedState(); 1595 } 1596 } 1597 } 1598 1599 /** 1600 * Returns the list's text filter, if available. 1601 * @return the list's text filter or null if filtering isn't enabled 1602 */ 1603 public CharSequence getTextFilter() { 1604 if (mTextFilterEnabled && mTextFilter != null) { 1605 return mTextFilter.getText(); 1606 } 1607 return null; 1608 } 1609 1610 @Override 1611 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 1612 super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); 1613 if (gainFocus && mSelectedPosition < 0 && !isInTouchMode()) { 1614 resurrectSelection(); 1615 } 1616 } 1617 1618 @Override 1619 public void requestLayout() { 1620 if (!mBlockLayoutRequests && !mInLayout) { 1621 super.requestLayout(); 1622 } 1623 } 1624 1625 /** 1626 * The list is empty. Clear everything out. 1627 */ 1628 void resetList() { 1629 removeAllViewsInLayout(); 1630 mFirstPosition = 0; 1631 mDataChanged = false; 1632 mNeedSync = false; 1633 mOldSelectedPosition = INVALID_POSITION; 1634 mOldSelectedRowId = INVALID_ROW_ID; 1635 setSelectedPositionInt(INVALID_POSITION); 1636 setNextSelectedPositionInt(INVALID_POSITION); 1637 mSelectedTop = 0; 1638 mSelectorShowing = false; 1639 mSelectorPosition = INVALID_POSITION; 1640 mSelectorRect.setEmpty(); 1641 invalidate(); 1642 } 1643 1644 @Override 1645 protected int computeVerticalScrollExtent() { 1646 final int count = getChildCount(); 1647 if (count > 0) { 1648 if (mSmoothScrollbarEnabled) { 1649 int extent = count * 100; 1650 1651 View view = getChildAt(0); 1652 final int top = view.getTop(); 1653 int height = view.getHeight(); 1654 if (height > 0) { 1655 extent += (top * 100) / height; 1656 } 1657 1658 view = getChildAt(count - 1); 1659 final int bottom = view.getBottom(); 1660 height = view.getHeight(); 1661 if (height > 0) { 1662 extent -= ((bottom - getHeight()) * 100) / height; 1663 } 1664 1665 return extent; 1666 } else { 1667 return 1; 1668 } 1669 } 1670 return 0; 1671 } 1672 1673 @Override 1674 protected int computeVerticalScrollOffset() { 1675 final int firstPosition = mFirstPosition; 1676 final int childCount = getChildCount(); 1677 if (firstPosition >= 0 && childCount > 0) { 1678 if (mSmoothScrollbarEnabled) { 1679 final View view = getChildAt(0); 1680 final int top = view.getTop(); 1681 int height = view.getHeight(); 1682 if (height > 0) { 1683 return Math.max(firstPosition * 100 - (top * 100) / height + 1684 (int)((float)mScrollY / getHeight() * mItemCount * 100), 0); 1685 } 1686 } else { 1687 int index; 1688 final int count = mItemCount; 1689 if (firstPosition == 0) { 1690 index = 0; 1691 } else if (firstPosition + childCount == count) { 1692 index = count; 1693 } else { 1694 index = firstPosition + childCount / 2; 1695 } 1696 return (int) (firstPosition + childCount * (index / (float) count)); 1697 } 1698 } 1699 return 0; 1700 } 1701 1702 @Override 1703 protected int computeVerticalScrollRange() { 1704 int result; 1705 if (mSmoothScrollbarEnabled) { 1706 result = Math.max(mItemCount * 100, 0); 1707 if (mScrollY != 0) { 1708 // Compensate for overscroll 1709 result += Math.abs((int) ((float) mScrollY / getHeight() * mItemCount * 100)); 1710 } 1711 } else { 1712 result = mItemCount; 1713 } 1714 return result; 1715 } 1716 1717 @Override 1718 protected float getTopFadingEdgeStrength() { 1719 final int count = getChildCount(); 1720 final float fadeEdge = super.getTopFadingEdgeStrength(); 1721 if (count == 0) { 1722 return fadeEdge; 1723 } else { 1724 if (mFirstPosition > 0) { 1725 return 1.0f; 1726 } 1727 1728 final int top = getChildAt(0).getTop(); 1729 final float fadeLength = (float) getVerticalFadingEdgeLength(); 1730 return top < mPaddingTop ? (float) -(top - mPaddingTop) / fadeLength : fadeEdge; 1731 } 1732 } 1733 1734 @Override 1735 protected float getBottomFadingEdgeStrength() { 1736 final int count = getChildCount(); 1737 final float fadeEdge = super.getBottomFadingEdgeStrength(); 1738 if (count == 0) { 1739 return fadeEdge; 1740 } else { 1741 if (mFirstPosition + count - 1 < mItemCount - 1) { 1742 return 1.0f; 1743 } 1744 1745 final int bottom = getChildAt(count - 1).getBottom(); 1746 final int height = getHeight(); 1747 final float fadeLength = (float) getVerticalFadingEdgeLength(); 1748 return bottom > height - mPaddingBottom ? 1749 (float) (bottom - height + mPaddingBottom) / fadeLength : fadeEdge; 1750 } 1751 } 1752 1753 @Override 1754 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 1755 if (mSelector == null) { 1756 useDefaultSelector(); 1757 } 1758 final Rect listPadding = mListPadding; 1759 listPadding.left = mSelectionLeftPadding + mPaddingLeft; 1760 listPadding.top = mSelectionTopPadding + mPaddingTop; 1761 listPadding.right = mSelectionRightPadding + mPaddingRight; 1762 listPadding.bottom = mSelectionBottomPadding + mPaddingBottom; 1763 1764 // Check if our previous measured size was at a point where we should scroll later. 1765 if (mTranscriptMode == TRANSCRIPT_MODE_NORMAL) { 1766 final int childCount = getChildCount(); 1767 final int listBottom = getBottom() - getPaddingBottom(); 1768 final View lastChild = getChildAt(childCount - 1); 1769 final int lastBottom = lastChild != null ? lastChild.getBottom() : listBottom; 1770 mForceTranscriptScroll = mFirstPosition + childCount >= mOldItemCount && 1771 lastBottom <= listBottom; 1772 } 1773 } 1774 1775 /** 1776 * Subclasses should NOT override this method but 1777 * {@link #layoutChildren()} instead. 1778 */ 1779 @Override 1780 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1781 super.onLayout(changed, l, t, r, b); 1782 mInLayout = true; 1783 if (changed) { 1784 int childCount = getChildCount(); 1785 for (int i = 0; i < childCount; i++) { 1786 getChildAt(i).forceLayout(); 1787 } 1788 mRecycler.markChildrenDirty(); 1789 } 1790 1791 if (mFastScroller != null && mItemCount != mOldItemCount) { 1792 mFastScroller.onItemCountChanged(mOldItemCount, mItemCount); 1793 } 1794 1795 layoutChildren(); 1796 mInLayout = false; 1797 1798 mOverscrollMax = (b - t) / OVERSCROLL_LIMIT_DIVISOR; 1799 } 1800 1801 /** 1802 * @hide 1803 */ 1804 @Override 1805 protected boolean setFrame(int left, int top, int right, int bottom) { 1806 final boolean changed = super.setFrame(left, top, right, bottom); 1807 1808 if (changed) { 1809 // Reposition the popup when the frame has changed. This includes 1810 // translating the widget, not just changing its dimension. The 1811 // filter popup needs to follow the widget. 1812 final boolean visible = getWindowVisibility() == View.VISIBLE; 1813 if (mFiltered && visible && mPopup != null && mPopup.isShowing()) { 1814 positionPopup(); 1815 } 1816 } 1817 1818 return changed; 1819 } 1820 1821 /** 1822 * Subclasses must override this method to layout their children. 1823 */ 1824 protected void layoutChildren() { 1825 } 1826 1827 void updateScrollIndicators() { 1828 if (mScrollUp != null) { 1829 boolean canScrollUp; 1830 // 0th element is not visible 1831 canScrollUp = mFirstPosition > 0; 1832 1833 // ... Or top of 0th element is not visible 1834 if (!canScrollUp) { 1835 if (getChildCount() > 0) { 1836 View child = getChildAt(0); 1837 canScrollUp = child.getTop() < mListPadding.top; 1838 } 1839 } 1840 1841 mScrollUp.setVisibility(canScrollUp ? View.VISIBLE : View.INVISIBLE); 1842 } 1843 1844 if (mScrollDown != null) { 1845 boolean canScrollDown; 1846 int count = getChildCount(); 1847 1848 // Last item is not visible 1849 canScrollDown = (mFirstPosition + count) < mItemCount; 1850 1851 // ... Or bottom of the last element is not visible 1852 if (!canScrollDown && count > 0) { 1853 View child = getChildAt(count - 1); 1854 canScrollDown = child.getBottom() > mBottom - mListPadding.bottom; 1855 } 1856 1857 mScrollDown.setVisibility(canScrollDown ? View.VISIBLE : View.INVISIBLE); 1858 } 1859 } 1860 1861 @Override 1862 @ViewDebug.ExportedProperty 1863 public View getSelectedView() { 1864 if (mItemCount > 0 && mSelectedPosition >= 0) { 1865 return getChildAt(mSelectedPosition - mFirstPosition); 1866 } else { 1867 return null; 1868 } 1869 } 1870 1871 /** 1872 * List padding is the maximum of the normal view's padding and the padding of the selector. 1873 * 1874 * @see android.view.View#getPaddingTop() 1875 * @see #getSelector() 1876 * 1877 * @return The top list padding. 1878 */ 1879 public int getListPaddingTop() { 1880 return mListPadding.top; 1881 } 1882 1883 /** 1884 * List padding is the maximum of the normal view's padding and the padding of the selector. 1885 * 1886 * @see android.view.View#getPaddingBottom() 1887 * @see #getSelector() 1888 * 1889 * @return The bottom list padding. 1890 */ 1891 public int getListPaddingBottom() { 1892 return mListPadding.bottom; 1893 } 1894 1895 /** 1896 * List padding is the maximum of the normal view's padding and the padding of the selector. 1897 * 1898 * @see android.view.View#getPaddingLeft() 1899 * @see #getSelector() 1900 * 1901 * @return The left list padding. 1902 */ 1903 public int getListPaddingLeft() { 1904 return mListPadding.left; 1905 } 1906 1907 /** 1908 * List padding is the maximum of the normal view's padding and the padding of the selector. 1909 * 1910 * @see android.view.View#getPaddingRight() 1911 * @see #getSelector() 1912 * 1913 * @return The right list padding. 1914 */ 1915 public int getListPaddingRight() { 1916 return mListPadding.right; 1917 } 1918 1919 /** 1920 * Get a view and have it show the data associated with the specified 1921 * position. This is called when we have already discovered that the view is 1922 * not available for reuse in the recycle bin. The only choices left are 1923 * converting an old view or making a new one. 1924 * 1925 * @param position The position to display 1926 * @param isScrap Array of at least 1 boolean, the first entry will become true if 1927 * the returned view was taken from the scrap heap, false if otherwise. 1928 * 1929 * @return A view displaying the data associated with the specified position 1930 */ 1931 View obtainView(int position, boolean[] isScrap) { 1932 isScrap[0] = false; 1933 View scrapView; 1934 1935 scrapView = mRecycler.getScrapView(position); 1936 1937 View child; 1938 if (scrapView != null) { 1939 if (ViewDebug.TRACE_RECYCLER) { 1940 ViewDebug.trace(scrapView, ViewDebug.RecyclerTraceType.RECYCLE_FROM_SCRAP_HEAP, 1941 position, -1); 1942 } 1943 1944 child = mAdapter.getView(position, scrapView, this); 1945 1946 if (ViewDebug.TRACE_RECYCLER) { 1947 ViewDebug.trace(child, ViewDebug.RecyclerTraceType.BIND_VIEW, 1948 position, getChildCount()); 1949 } 1950 1951 if (child != scrapView) { 1952 mRecycler.addScrapView(scrapView, position); 1953 if (mCacheColorHint != 0) { 1954 child.setDrawingCacheBackgroundColor(mCacheColorHint); 1955 } 1956 if (ViewDebug.TRACE_RECYCLER) { 1957 ViewDebug.trace(scrapView, ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, 1958 position, -1); 1959 } 1960 } else { 1961 isScrap[0] = true; 1962 child.dispatchFinishTemporaryDetach(); 1963 } 1964 } else { 1965 child = mAdapter.getView(position, null, this); 1966 if (mCacheColorHint != 0) { 1967 child.setDrawingCacheBackgroundColor(mCacheColorHint); 1968 } 1969 if (ViewDebug.TRACE_RECYCLER) { 1970 ViewDebug.trace(child, ViewDebug.RecyclerTraceType.NEW_VIEW, 1971 position, getChildCount()); 1972 } 1973 } 1974 1975 return child; 1976 } 1977 1978 void positionSelector(int position, View sel) { 1979 if (position != INVALID_POSITION) { 1980 mSelectorPosition = position; 1981 } 1982 1983 final Rect selectorRect = mSelectorRect; 1984 selectorRect.set(sel.getLeft(), sel.getTop(), sel.getRight(), sel.getBottom()); 1985 if (sel instanceof SelectionBoundsAdjuster) { 1986 ((SelectionBoundsAdjuster)sel).adjustListItemSelectionBounds(selectorRect); 1987 } 1988 positionSelector(selectorRect.left, selectorRect.top, selectorRect.right, 1989 selectorRect.bottom); 1990 1991 final boolean isChildViewEnabled = mIsChildViewEnabled; 1992 if (sel.isEnabled() != isChildViewEnabled) { 1993 mIsChildViewEnabled = !isChildViewEnabled; 1994 if (mSelectorShowing) { 1995 refreshDrawableState(); 1996 } 1997 } 1998 } 1999 2000 private void positionSelector(int l, int t, int r, int b) { 2001 mSelectorRect.set(l - mSelectionLeftPadding, t - mSelectionTopPadding, r 2002 + mSelectionRightPadding, b + mSelectionBottomPadding); 2003 } 2004 2005 @Override 2006 protected void dispatchDraw(Canvas canvas) { 2007 int saveCount = 0; 2008 final boolean clipToPadding = (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK; 2009 if (clipToPadding) { 2010 saveCount = canvas.save(); 2011 final int scrollX = mScrollX; 2012 final int scrollY = mScrollY; 2013 canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop, 2014 scrollX + mRight - mLeft - mPaddingRight, 2015 scrollY + mBottom - mTop - mPaddingBottom); 2016 mGroupFlags &= ~CLIP_TO_PADDING_MASK; 2017 } 2018 2019 final boolean drawSelectorOnTop = mDrawSelectorOnTop; 2020 if (!drawSelectorOnTop) { 2021 drawSelector(canvas); 2022 } 2023 2024 super.dispatchDraw(canvas); 2025 2026 if (drawSelectorOnTop) { 2027 drawSelector(canvas); 2028 } 2029 2030 if (clipToPadding) { 2031 canvas.restoreToCount(saveCount); 2032 mGroupFlags |= CLIP_TO_PADDING_MASK; 2033 } 2034 } 2035 2036 @Override 2037 protected boolean isPaddingOffsetRequired() { 2038 return (mGroupFlags & CLIP_TO_PADDING_MASK) != CLIP_TO_PADDING_MASK; 2039 } 2040 2041 @Override 2042 protected int getLeftPaddingOffset() { 2043 return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : -mPaddingLeft; 2044 } 2045 2046 @Override 2047 protected int getTopPaddingOffset() { 2048 return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : -mPaddingTop; 2049 } 2050 2051 @Override 2052 protected int getRightPaddingOffset() { 2053 return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : mPaddingRight; 2054 } 2055 2056 @Override 2057 protected int getBottomPaddingOffset() { 2058 return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : mPaddingBottom; 2059 } 2060 2061 @Override 2062 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 2063 if (getChildCount() > 0) { 2064 mDataChanged = true; 2065 rememberSyncState(); 2066 } 2067 2068 if (mFastScroller != null) { 2069 mFastScroller.onSizeChanged(w, h, oldw, oldh); 2070 } 2071 } 2072 2073 /** 2074 * @return True if the current touch mode requires that we draw the selector in the pressed 2075 * state. 2076 */ 2077 boolean touchModeDrawsInPressedState() { 2078 // FIXME use isPressed for this 2079 switch (mTouchMode) { 2080 case TOUCH_MODE_TAP: 2081 case TOUCH_MODE_DONE_WAITING: 2082 return true; 2083 default: 2084 return false; 2085 } 2086 } 2087 2088 /** 2089 * Indicates whether this view is in a state where the selector should be drawn. This will 2090 * happen if we have focus but are not in touch mode, or we are in the middle of displaying 2091 * the pressed state for an item. 2092 * 2093 * @return True if the selector should be shown 2094 */ 2095 boolean shouldShowSelector() { 2096 return (hasFocus() && !isInTouchMode()) || touchModeDrawsInPressedState(); 2097 } 2098 2099 private void drawSelector(Canvas canvas) { 2100 if (!mSelectorRect.isEmpty()) { 2101 final Drawable selector = mSelector; 2102 selector.setBounds(mSelectorRect); 2103 selector.draw(canvas); 2104 } 2105 } 2106 2107 /** 2108 * Controls whether the selection highlight drawable should be drawn on top of the item or 2109 * behind it. 2110 * 2111 * @param onTop If true, the selector will be drawn on the item it is highlighting. The default 2112 * is false. 2113 * 2114 * @attr ref android.R.styleable#AbsListView_drawSelectorOnTop 2115 */ 2116 public void setDrawSelectorOnTop(boolean onTop) { 2117 mDrawSelectorOnTop = onTop; 2118 } 2119 2120 /** 2121 * Set a Drawable that should be used to highlight the currently selected item. 2122 * 2123 * @param resID A Drawable resource to use as the selection highlight. 2124 * 2125 * @attr ref android.R.styleable#AbsListView_listSelector 2126 */ 2127 public void setSelector(int resID) { 2128 setSelector(getResources().getDrawable(resID)); 2129 } 2130 2131 public void setSelector(Drawable sel) { 2132 if (mSelector != null) { 2133 mSelector.setCallback(null); 2134 unscheduleDrawable(mSelector); 2135 } 2136 mSelector = sel; 2137 Rect padding = new Rect(); 2138 sel.getPadding(padding); 2139 mSelectionLeftPadding = padding.left; 2140 mSelectionTopPadding = padding.top; 2141 mSelectionRightPadding = padding.right; 2142 mSelectionBottomPadding = padding.bottom; 2143 sel.setCallback(this); 2144 updateSelectorState(); 2145 } 2146 2147 /** 2148 * Returns the selector {@link android.graphics.drawable.Drawable} that is used to draw the 2149 * selection in the list. 2150 * 2151 * @return the drawable used to display the selector 2152 */ 2153 public Drawable getSelector() { 2154 return mSelector; 2155 } 2156 2157 /** 2158 * Sets the selector state to "pressed" and posts a CheckForKeyLongPress to see if 2159 * this is a long press. 2160 */ 2161 void keyPressed() { 2162 if (!isEnabled() || !isClickable()) { 2163 return; 2164 } 2165 2166 Drawable selector = mSelector; 2167 Rect selectorRect = mSelectorRect; 2168 if (selector != null && (isFocused() || touchModeDrawsInPressedState()) 2169 && !selectorRect.isEmpty()) { 2170 2171 final View v = getChildAt(mSelectedPosition - mFirstPosition); 2172 2173 if (v != null) { 2174 if (v.hasFocusable()) return; 2175 v.setPressed(true); 2176 } 2177 setPressed(true); 2178 2179 final boolean longClickable = isLongClickable(); 2180 Drawable d = selector.getCurrent(); 2181 if (d != null && d instanceof TransitionDrawable) { 2182 if (longClickable) { 2183 ((TransitionDrawable) d).startTransition( 2184 ViewConfiguration.getLongPressTimeout()); 2185 } else { 2186 ((TransitionDrawable) d).resetTransition(); 2187 } 2188 } 2189 if (longClickable && !mDataChanged) { 2190 if (mPendingCheckForKeyLongPress == null) { 2191 mPendingCheckForKeyLongPress = new CheckForKeyLongPress(); 2192 } 2193 mPendingCheckForKeyLongPress.rememberWindowAttachCount(); 2194 postDelayed(mPendingCheckForKeyLongPress, ViewConfiguration.getLongPressTimeout()); 2195 } 2196 } 2197 } 2198 2199 public void setScrollIndicators(View up, View down) { 2200 mScrollUp = up; 2201 mScrollDown = down; 2202 } 2203 2204 void updateSelectorState() { 2205 if (mSelector != null) { 2206 if (shouldShowSelector()) { 2207 mSelector.setState(getDrawableState()); 2208 } else { 2209 mSelector.setState(StateSet.NOTHING); 2210 } 2211 } 2212 } 2213 2214 @Override 2215 protected void drawableStateChanged() { 2216 super.drawableStateChanged(); 2217 updateSelectorState(); 2218 } 2219 2220 @Override 2221 protected int[] onCreateDrawableState(int extraSpace) { 2222 // If the child view is enabled then do the default behavior. 2223 if (mIsChildViewEnabled) { 2224 // Common case 2225 return super.onCreateDrawableState(extraSpace); 2226 } 2227 2228 // The selector uses this View's drawable state. The selected child view 2229 // is disabled, so we need to remove the enabled state from the drawable 2230 // states. 2231 final int enabledState = ENABLED_STATE_SET[0]; 2232 2233 // If we don't have any extra space, it will return one of the static state arrays, 2234 // and clearing the enabled state on those arrays is a bad thing! If we specify 2235 // we need extra space, it will create+copy into a new array that safely mutable. 2236 int[] state = super.onCreateDrawableState(extraSpace + 1); 2237 int enabledPos = -1; 2238 for (int i = state.length - 1; i >= 0; i--) { 2239 if (state[i] == enabledState) { 2240 enabledPos = i; 2241 break; 2242 } 2243 } 2244 2245 // Remove the enabled state 2246 if (enabledPos >= 0) { 2247 System.arraycopy(state, enabledPos + 1, state, enabledPos, 2248 state.length - enabledPos - 1); 2249 } 2250 2251 return state; 2252 } 2253 2254 @Override 2255 public boolean verifyDrawable(Drawable dr) { 2256 return mSelector == dr || super.verifyDrawable(dr); 2257 } 2258 2259 @Override 2260 public void jumpDrawablesToCurrentState() { 2261 super.jumpDrawablesToCurrentState(); 2262 if (mSelector != null) mSelector.jumpToCurrentState(); 2263 } 2264 2265 @Override 2266 protected void onAttachedToWindow() { 2267 super.onAttachedToWindow(); 2268 2269 final ViewTreeObserver treeObserver = getViewTreeObserver(); 2270 if (treeObserver != null) { 2271 treeObserver.addOnTouchModeChangeListener(this); 2272 if (mTextFilterEnabled && mPopup != null && !mGlobalLayoutListenerAddedFilter) { 2273 treeObserver.addOnGlobalLayoutListener(this); 2274 } 2275 } 2276 2277 if (mAdapter != null && mDataSetObserver == null) { 2278 mDataSetObserver = new AdapterDataSetObserver(); 2279 mAdapter.registerDataSetObserver(mDataSetObserver); 2280 2281 // Data may have changed while we were detached. Refresh. 2282 mDataChanged = true; 2283 mOldItemCount = mItemCount; 2284 mItemCount = mAdapter.getCount(); 2285 } 2286 } 2287 2288 @Override 2289 protected void onDetachedFromWindow() { 2290 super.onDetachedFromWindow(); 2291 2292 // Dismiss the popup in case onSaveInstanceState() was not invoked 2293 dismissPopup(); 2294 2295 // Detach any view left in the scrap heap 2296 mRecycler.clear(); 2297 2298 final ViewTreeObserver treeObserver = getViewTreeObserver(); 2299 if (treeObserver != null) { 2300 treeObserver.removeOnTouchModeChangeListener(this); 2301 if (mTextFilterEnabled && mPopup != null) { 2302 treeObserver.removeGlobalOnLayoutListener(this); 2303 mGlobalLayoutListenerAddedFilter = false; 2304 } 2305 } 2306 2307 if (mAdapter != null) { 2308 mAdapter.unregisterDataSetObserver(mDataSetObserver); 2309 mDataSetObserver = null; 2310 } 2311 2312 if (mScrollStrictSpan != null) { 2313 mScrollStrictSpan.finish(); 2314 mScrollStrictSpan = null; 2315 } 2316 2317 if (mFlingStrictSpan != null) { 2318 mFlingStrictSpan.finish(); 2319 mFlingStrictSpan = null; 2320 } 2321 2322 if (mFlingRunnable != null) { 2323 removeCallbacks(mFlingRunnable); 2324 } 2325 2326 if (mPositionScroller != null) { 2327 mPositionScroller.stop(); 2328 } 2329 2330 if (mClearScrollingCache != null) { 2331 removeCallbacks(mClearScrollingCache); 2332 } 2333 2334 if (mPerformClick != null) { 2335 removeCallbacks(mPerformClick); 2336 } 2337 2338 if (mTouchModeReset != null) { 2339 removeCallbacks(mTouchModeReset); 2340 mTouchModeReset = null; 2341 } 2342 } 2343 2344 @Override 2345 public void onWindowFocusChanged(boolean hasWindowFocus) { 2346 super.onWindowFocusChanged(hasWindowFocus); 2347 2348 final int touchMode = isInTouchMode() ? TOUCH_MODE_ON : TOUCH_MODE_OFF; 2349 2350 if (!hasWindowFocus) { 2351 setChildrenDrawingCacheEnabled(false); 2352 if (mFlingRunnable != null) { 2353 removeCallbacks(mFlingRunnable); 2354 // let the fling runnable report it's new state which 2355 // should be idle 2356 mFlingRunnable.endFling(); 2357 if (mPositionScroller != null) { 2358 mPositionScroller.stop(); 2359 } 2360 if (mScrollY != 0) { 2361 mScrollY = 0; 2362 invalidateParentCaches(); 2363 finishGlows(); 2364 invalidate(); 2365 } 2366 } 2367 // Always hide the type filter 2368 dismissPopup(); 2369 2370 if (touchMode == TOUCH_MODE_OFF) { 2371 // Remember the last selected element 2372 mResurrectToPosition = mSelectedPosition; 2373 } 2374 } else { 2375 if (mFiltered && !mPopupHidden) { 2376 // Show the type filter only if a filter is in effect 2377 showPopup(); 2378 } 2379 2380 // If we changed touch mode since the last time we had focus 2381 if (touchMode != mLastTouchMode && mLastTouchMode != TOUCH_MODE_UNKNOWN) { 2382 // If we come back in trackball mode, we bring the selection back 2383 if (touchMode == TOUCH_MODE_OFF) { 2384 // This will trigger a layout 2385 resurrectSelection(); 2386 2387 // If we come back in touch mode, then we want to hide the selector 2388 } else { 2389 hideSelector(); 2390 mLayoutMode = LAYOUT_NORMAL; 2391 layoutChildren(); 2392 } 2393 } 2394 } 2395 2396 mLastTouchMode = touchMode; 2397 } 2398 2399 /** 2400 * Creates the ContextMenuInfo returned from {@link #getContextMenuInfo()}. This 2401 * methods knows the view, position and ID of the item that received the 2402 * long press. 2403 * 2404 * @param view The view that received the long press. 2405 * @param position The position of the item that received the long press. 2406 * @param id The ID of the item that received the long press. 2407 * @return The extra information that should be returned by 2408 * {@link #getContextMenuInfo()}. 2409 */ 2410 ContextMenuInfo createContextMenuInfo(View view, int position, long id) { 2411 return new AdapterContextMenuInfo(view, position, id); 2412 } 2413 2414 /** 2415 * A base class for Runnables that will check that their view is still attached to 2416 * the original window as when the Runnable was created. 2417 * 2418 */ 2419 private class WindowRunnnable { 2420 private int mOriginalAttachCount; 2421 2422 public void rememberWindowAttachCount() { 2423 mOriginalAttachCount = getWindowAttachCount(); 2424 } 2425 2426 public boolean sameWindow() { 2427 return hasWindowFocus() && getWindowAttachCount() == mOriginalAttachCount; 2428 } 2429 } 2430 2431 private class PerformClick extends WindowRunnnable implements Runnable { 2432 int mClickMotionPosition; 2433 2434 public void run() { 2435 // The data has changed since we posted this action in the event queue, 2436 // bail out before bad things happen 2437 if (mDataChanged) return; 2438 2439 final ListAdapter adapter = mAdapter; 2440 final int motionPosition = mClickMotionPosition; 2441 if (adapter != null && mItemCount > 0 && 2442 motionPosition != INVALID_POSITION && 2443 motionPosition < adapter.getCount() && sameWindow()) { 2444 final View view = getChildAt(motionPosition - mFirstPosition); 2445 // If there is no view, something bad happened (the view scrolled off the 2446 // screen, etc.) and we should cancel the click 2447 if (view != null) { 2448 performItemClick(view, motionPosition, adapter.getItemId(motionPosition)); 2449 } 2450 } 2451 } 2452 } 2453 2454 private class CheckForLongPress extends WindowRunnnable implements Runnable { 2455 public void run() { 2456 final int motionPosition = mMotionPosition; 2457 final View child = getChildAt(motionPosition - mFirstPosition); 2458 if (child != null) { 2459 final int longPressPosition = mMotionPosition; 2460 final long longPressId = mAdapter.getItemId(mMotionPosition); 2461 2462 boolean handled = false; 2463 if (sameWindow() && !mDataChanged) { 2464 handled = performLongPress(child, longPressPosition, longPressId); 2465 } 2466 if (handled) { 2467 mTouchMode = TOUCH_MODE_REST; 2468 setPressed(false); 2469 child.setPressed(false); 2470 } else { 2471 mTouchMode = TOUCH_MODE_DONE_WAITING; 2472 } 2473 } 2474 } 2475 } 2476 2477 private class CheckForKeyLongPress extends WindowRunnnable implements Runnable { 2478 public void run() { 2479 if (isPressed() && mSelectedPosition >= 0) { 2480 int index = mSelectedPosition - mFirstPosition; 2481 View v = getChildAt(index); 2482 2483 if (!mDataChanged) { 2484 boolean handled = false; 2485 if (sameWindow()) { 2486 handled = performLongPress(v, mSelectedPosition, mSelectedRowId); 2487 } 2488 if (handled) { 2489 setPressed(false); 2490 v.setPressed(false); 2491 } 2492 } else { 2493 setPressed(false); 2494 if (v != null) v.setPressed(false); 2495 } 2496 } 2497 } 2498 } 2499 2500 boolean performLongPress(final View child, 2501 final int longPressPosition, final long longPressId) { 2502 // CHOICE_MODE_MULTIPLE_MODAL takes over long press. 2503 if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) { 2504 if (mChoiceActionMode == null) { 2505 mChoiceActionMode = startActionMode(mMultiChoiceModeCallback); 2506 setItemChecked(longPressPosition, true); 2507 } 2508 // TODO Should we select the long pressed item if we were already in 2509 // selection mode? (i.e. treat it like an item click?) 2510 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 2511 return true; 2512 } 2513 2514 boolean handled = false; 2515 if (mOnItemLongClickListener != null) { 2516 handled = mOnItemLongClickListener.onItemLongClick(AbsListView.this, child, 2517 longPressPosition, longPressId); 2518 } 2519 if (!handled) { 2520 mContextMenuInfo = createContextMenuInfo(child, longPressPosition, longPressId); 2521 handled = super.showContextMenuForChild(AbsListView.this); 2522 } 2523 if (handled) { 2524 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 2525 } 2526 return handled; 2527 } 2528 2529 @Override 2530 protected ContextMenuInfo getContextMenuInfo() { 2531 return mContextMenuInfo; 2532 } 2533 2534 @Override 2535 public boolean showContextMenuForChild(View originalView) { 2536 final int longPressPosition = getPositionForView(originalView); 2537 if (longPressPosition >= 0) { 2538 final long longPressId = mAdapter.getItemId(longPressPosition); 2539 boolean handled = false; 2540 2541 if (mOnItemLongClickListener != null) { 2542 handled = mOnItemLongClickListener.onItemLongClick(AbsListView.this, originalView, 2543 longPressPosition, longPressId); 2544 } 2545 if (!handled) { 2546 mContextMenuInfo = createContextMenuInfo( 2547 getChildAt(longPressPosition - mFirstPosition), 2548 longPressPosition, longPressId); 2549 handled = super.showContextMenuForChild(originalView); 2550 } 2551 2552 return handled; 2553 } 2554 return false; 2555 } 2556 2557 @Override 2558 public boolean onKeyDown(int keyCode, KeyEvent event) { 2559 return false; 2560 } 2561 2562 @Override 2563 public boolean onKeyUp(int keyCode, KeyEvent event) { 2564 switch (keyCode) { 2565 case KeyEvent.KEYCODE_DPAD_CENTER: 2566 case KeyEvent.KEYCODE_ENTER: 2567 if (!isEnabled()) { 2568 return true; 2569 } 2570 if (isClickable() && isPressed() && 2571 mSelectedPosition >= 0 && mAdapter != null && 2572 mSelectedPosition < mAdapter.getCount()) { 2573 2574 final View view = getChildAt(mSelectedPosition - mFirstPosition); 2575 if (view != null) { 2576 performItemClick(view, mSelectedPosition, mSelectedRowId); 2577 view.setPressed(false); 2578 } 2579 setPressed(false); 2580 return true; 2581 } 2582 break; 2583 } 2584 return super.onKeyUp(keyCode, event); 2585 } 2586 2587 @Override 2588 protected void dispatchSetPressed(boolean pressed) { 2589 // Don't dispatch setPressed to our children. We call setPressed on ourselves to 2590 // get the selector in the right state, but we don't want to press each child. 2591 } 2592 2593 /** 2594 * Maps a point to a position in the list. 2595 * 2596 * @param x X in local coordinate 2597 * @param y Y in local coordinate 2598 * @return The position of the item which contains the specified point, or 2599 * {@link #INVALID_POSITION} if the point does not intersect an item. 2600 */ 2601 public int pointToPosition(int x, int y) { 2602 Rect frame = mTouchFrame; 2603 if (frame == null) { 2604 mTouchFrame = new Rect(); 2605 frame = mTouchFrame; 2606 } 2607 2608 final int count = getChildCount(); 2609 for (int i = count - 1; i >= 0; i--) { 2610 final View child = getChildAt(i); 2611 if (child.getVisibility() == View.VISIBLE) { 2612 child.getHitRect(frame); 2613 if (frame.contains(x, y)) { 2614 return mFirstPosition + i; 2615 } 2616 } 2617 } 2618 return INVALID_POSITION; 2619 } 2620 2621 2622 /** 2623 * Maps a point to a the rowId of the item which intersects that point. 2624 * 2625 * @param x X in local coordinate 2626 * @param y Y in local coordinate 2627 * @return The rowId of the item which contains the specified point, or {@link #INVALID_ROW_ID} 2628 * if the point does not intersect an item. 2629 */ 2630 public long pointToRowId(int x, int y) { 2631 int position = pointToPosition(x, y); 2632 if (position >= 0) { 2633 return mAdapter.getItemId(position); 2634 } 2635 return INVALID_ROW_ID; 2636 } 2637 2638 final class CheckForTap implements Runnable { 2639 public void run() { 2640 if (mTouchMode == TOUCH_MODE_DOWN) { 2641 mTouchMode = TOUCH_MODE_TAP; 2642 final View child = getChildAt(mMotionPosition - mFirstPosition); 2643 if (child != null && !child.hasFocusable()) { 2644 mLayoutMode = LAYOUT_NORMAL; 2645 2646 if (!mDataChanged) { 2647 child.setPressed(true); 2648 setPressed(true); 2649 layoutChildren(); 2650 positionSelector(mMotionPosition, child); 2651 refreshDrawableState(); 2652 2653 final int longPressTimeout = ViewConfiguration.getLongPressTimeout(); 2654 final boolean longClickable = isLongClickable(); 2655 2656 if (mSelector != null) { 2657 Drawable d = mSelector.getCurrent(); 2658 if (d != null && d instanceof TransitionDrawable) { 2659 if (longClickable) { 2660 ((TransitionDrawable) d).startTransition(longPressTimeout); 2661 } else { 2662 ((TransitionDrawable) d).resetTransition(); 2663 } 2664 } 2665 } 2666 2667 if (longClickable) { 2668 if (mPendingCheckForLongPress == null) { 2669 mPendingCheckForLongPress = new CheckForLongPress(); 2670 } 2671 mPendingCheckForLongPress.rememberWindowAttachCount(); 2672 postDelayed(mPendingCheckForLongPress, longPressTimeout); 2673 } else { 2674 mTouchMode = TOUCH_MODE_DONE_WAITING; 2675 } 2676 } else { 2677 mTouchMode = TOUCH_MODE_DONE_WAITING; 2678 } 2679 } 2680 } 2681 } 2682 } 2683 2684 private boolean startScrollIfNeeded(int deltaY) { 2685 // Check if we have moved far enough that it looks more like a 2686 // scroll than a tap 2687 final int distance = Math.abs(deltaY); 2688 final boolean overscroll = mScrollY != 0; 2689 if (overscroll || distance > mTouchSlop) { 2690 createScrollingCache(); 2691 mTouchMode = overscroll ? TOUCH_MODE_OVERSCROLL : TOUCH_MODE_SCROLL; 2692 mMotionCorrection = deltaY; 2693 final Handler handler = getHandler(); 2694 // Handler should not be null unless the AbsListView is not attached to a 2695 // window, which would make it very hard to scroll it... but the monkeys 2696 // say it's possible. 2697 if (handler != null) { 2698 handler.removeCallbacks(mPendingCheckForLongPress); 2699 } 2700 setPressed(false); 2701 View motionView = getChildAt(mMotionPosition - mFirstPosition); 2702 if (motionView != null) { 2703 motionView.setPressed(false); 2704 } 2705 reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); 2706 // Time to start stealing events! Once we've stolen them, don't let anyone 2707 // steal from us 2708 requestDisallowInterceptTouchEvent(true); 2709 return true; 2710 } 2711 2712 return false; 2713 } 2714 2715 public void onTouchModeChanged(boolean isInTouchMode) { 2716 if (isInTouchMode) { 2717 // Get rid of the selection when we enter touch mode 2718 hideSelector(); 2719 // Layout, but only if we already have done so previously. 2720 // (Otherwise may clobber a LAYOUT_SYNC layout that was requested to restore 2721 // state.) 2722 if (getHeight() > 0 && getChildCount() > 0) { 2723 // We do not lose focus initiating a touch (since AbsListView is focusable in 2724 // touch mode). Force an initial layout to get rid of the selection. 2725 layoutChildren(); 2726 } 2727 } else { 2728 int touchMode = mTouchMode; 2729 if (touchMode == TOUCH_MODE_OVERSCROLL || touchMode == TOUCH_MODE_OVERFLING) { 2730 if (mFlingRunnable != null) { 2731 mFlingRunnable.endFling(); 2732 } 2733 if (mPositionScroller != null) { 2734 mPositionScroller.stop(); 2735 } 2736 2737 if (mScrollY != 0) { 2738 mScrollY = 0; 2739 invalidateParentCaches(); 2740 finishGlows(); 2741 invalidate(); 2742 } 2743 } 2744 } 2745 } 2746 2747 @Override 2748 public boolean onTouchEvent(MotionEvent ev) { 2749 if (!isEnabled()) { 2750 // A disabled view that is clickable still consumes the touch 2751 // events, it just doesn't respond to them. 2752 return isClickable() || isLongClickable(); 2753 } 2754 2755 if (mFastScroller != null) { 2756 boolean intercepted = mFastScroller.onTouchEvent(ev); 2757 if (intercepted) { 2758 return true; 2759 } 2760 } 2761 2762 final int action = ev.getAction(); 2763 2764 View v; 2765 int deltaY; 2766 2767 if (mVelocityTracker == null) { 2768 mVelocityTracker = VelocityTracker.obtain(); 2769 } 2770 mVelocityTracker.addMovement(ev); 2771 2772 switch (action & MotionEvent.ACTION_MASK) { 2773 case MotionEvent.ACTION_DOWN: { 2774 switch (mTouchMode) { 2775 case TOUCH_MODE_OVERFLING: { 2776 mFlingRunnable.endFling(); 2777 if (mPositionScroller != null) { 2778 mPositionScroller.stop(); 2779 } 2780 mTouchMode = TOUCH_MODE_OVERSCROLL; 2781 mMotionY = mLastY = (int) ev.getY(); 2782 mMotionCorrection = 0; 2783 mActivePointerId = ev.getPointerId(0); 2784 break; 2785 } 2786 2787 default: { 2788 mActivePointerId = ev.getPointerId(0); 2789 final int x = (int) ev.getX(); 2790 final int y = (int) ev.getY(); 2791 int motionPosition = pointToPosition(x, y); 2792 if (!mDataChanged) { 2793 if ((mTouchMode != TOUCH_MODE_FLING) && (motionPosition >= 0) 2794 && (getAdapter().isEnabled(motionPosition))) { 2795 // User clicked on an actual view (and was not stopping a fling). It might be a 2796 // click or a scroll. Assume it is a click until proven otherwise 2797 mTouchMode = TOUCH_MODE_DOWN; 2798 // FIXME Debounce 2799 if (mPendingCheckForTap == null) { 2800 mPendingCheckForTap = new CheckForTap(); 2801 } 2802 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 2803 } else { 2804 if (ev.getEdgeFlags() != 0 && motionPosition < 0) { 2805 // If we couldn't find a view to click on, but the down event was touching 2806 // the edge, we will bail out and try again. This allows the edge correcting 2807 // code in ViewRoot to try to find a nearby view to select 2808 return false; 2809 } 2810 2811 if (mTouchMode == TOUCH_MODE_FLING) { 2812 // Stopped a fling. It is a scroll. 2813 createScrollingCache(); 2814 mTouchMode = TOUCH_MODE_SCROLL; 2815 mMotionCorrection = 0; 2816 motionPosition = findMotionRow(y); 2817 mFlingRunnable.flywheelTouch(); 2818 } 2819 } 2820 } 2821 2822 if (motionPosition >= 0) { 2823 // Remember where the motion event started 2824 v = getChildAt(motionPosition - mFirstPosition); 2825 mMotionViewOriginalTop = v.getTop(); 2826 } 2827 mMotionX = x; 2828 mMotionY = y; 2829 mMotionPosition = motionPosition; 2830 mLastY = Integer.MIN_VALUE; 2831 break; 2832 } 2833 } 2834 break; 2835 } 2836 2837 case MotionEvent.ACTION_MOVE: { 2838 final int pointerIndex = ev.findPointerIndex(mActivePointerId); 2839 final int y = (int) ev.getY(pointerIndex); 2840 deltaY = y - mMotionY; 2841 switch (mTouchMode) { 2842 case TOUCH_MODE_DOWN: 2843 case TOUCH_MODE_TAP: 2844 case TOUCH_MODE_DONE_WAITING: 2845 // Check if we have moved far enough that it looks more like a 2846 // scroll than a tap 2847 startScrollIfNeeded(deltaY); 2848 break; 2849 case TOUCH_MODE_SCROLL: 2850 if (PROFILE_SCROLLING) { 2851 if (!mScrollProfilingStarted) { 2852 Debug.startMethodTracing("AbsListViewScroll"); 2853 mScrollProfilingStarted = true; 2854 } 2855 } 2856 2857 if (mScrollStrictSpan == null) { 2858 // If it's non-null, we're already in a scroll. 2859 mScrollStrictSpan = StrictMode.enterCriticalSpan("AbsListView-scroll"); 2860 } 2861 2862 if (y != mLastY) { 2863 // We may be here after stopping a fling and continuing to scroll. 2864 // If so, we haven't disallowed intercepting touch events yet. 2865 // Make sure that we do so in case we're in a parent that can intercept. 2866 if ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) == 0 && 2867 Math.abs(deltaY) > mTouchSlop) { 2868 requestDisallowInterceptTouchEvent(true); 2869 } 2870 2871 final int rawDeltaY = deltaY; 2872 deltaY -= mMotionCorrection; 2873 int incrementalDeltaY = mLastY != Integer.MIN_VALUE ? y - mLastY : deltaY; 2874 2875 final int motionIndex; 2876 if (mMotionPosition >= 0) { 2877 motionIndex = mMotionPosition - mFirstPosition; 2878 } else { 2879 // If we don't have a motion position that we can reliably track, 2880 // pick something in the middle to make a best guess at things below. 2881 motionIndex = getChildCount() / 2; 2882 } 2883 2884 int motionViewPrevTop = 0; 2885 View motionView = this.getChildAt(motionIndex); 2886 if (motionView != null) { 2887 motionViewPrevTop = motionView.getTop(); 2888 } 2889 2890 // No need to do all this work if we're not going to move anyway 2891 boolean atEdge = false; 2892 if (incrementalDeltaY != 0) { 2893 atEdge = trackMotionScroll(deltaY, incrementalDeltaY); 2894 } 2895 2896 // Check to see if we have bumped into the scroll limit 2897 motionView = this.getChildAt(motionIndex); 2898 if (motionView != null) { 2899 // Check if the top of the motion view is where it is 2900 // supposed to be 2901 final int motionViewRealTop = motionView.getTop(); 2902 if (atEdge) { 2903 // Apply overscroll 2904 2905 int overscroll = -incrementalDeltaY - 2906 (motionViewRealTop - motionViewPrevTop); 2907 overScrollBy(0, overscroll, 0, mScrollY, 0, 0, 2908 0, mOverscrollDistance, true); 2909 if (Math.abs(mOverscrollDistance) == Math.abs(mScrollY)) { 2910 // Don't allow overfling if we're at the edge. 2911 mVelocityTracker.clear(); 2912 } 2913 2914 final int overscrollMode = getOverScrollMode(); 2915 if (overscrollMode == OVER_SCROLL_ALWAYS || 2916 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && 2917 !contentFits())) { 2918 mDirection = 0; // Reset when entering overscroll. 2919 mTouchMode = TOUCH_MODE_OVERSCROLL; 2920 if (rawDeltaY > 0) { 2921 mEdgeGlowTop.onPull((float) overscroll / getHeight()); 2922 if (!mEdgeGlowBottom.isFinished()) { 2923 mEdgeGlowBottom.onRelease(); 2924 } 2925 } else if (rawDeltaY < 0) { 2926 mEdgeGlowBottom.onPull((float) overscroll / getHeight()); 2927 if (!mEdgeGlowTop.isFinished()) { 2928 mEdgeGlowTop.onRelease(); 2929 } 2930 } 2931 } 2932 } 2933 mMotionY = y; 2934 invalidate(); 2935 } 2936 mLastY = y; 2937 } 2938 break; 2939 2940 case TOUCH_MODE_OVERSCROLL: 2941 if (y != mLastY) { 2942 final int rawDeltaY = deltaY; 2943 deltaY -= mMotionCorrection; 2944 int incrementalDeltaY = mLastY != Integer.MIN_VALUE ? y - mLastY : deltaY; 2945 2946 final int oldScroll = mScrollY; 2947 final int newScroll = oldScroll - incrementalDeltaY; 2948 int newDirection = y > mLastY ? 1 : -1; 2949 2950 if (mDirection == 0) { 2951 mDirection = newDirection; 2952 } 2953 2954 if (mDirection != newDirection) { 2955 // Coming back to 'real' list scrolling 2956 incrementalDeltaY = -newScroll; 2957 mScrollY = 0; 2958 invalidateParentIfNeeded(); 2959 2960 // No need to do all this work if we're not going to move anyway 2961 if (incrementalDeltaY != 0) { 2962 trackMotionScroll(incrementalDeltaY, incrementalDeltaY); 2963 } 2964 2965 // Check to see if we are back in 2966 View motionView = this.getChildAt(mMotionPosition - mFirstPosition); 2967 if (motionView != null) { 2968 mTouchMode = TOUCH_MODE_SCROLL; 2969 2970 // We did not scroll the full amount. Treat this essentially like the 2971 // start of a new touch scroll 2972 final int motionPosition = findClosestMotionRow(y); 2973 2974 mMotionCorrection = 0; 2975 motionView = getChildAt(motionPosition - mFirstPosition); 2976 mMotionViewOriginalTop = motionView.getTop(); 2977 mMotionY = y; 2978 mMotionPosition = motionPosition; 2979 } 2980 } else { 2981 overScrollBy(0, -incrementalDeltaY, 0, mScrollY, 0, 0, 2982 0, mOverscrollDistance, true); 2983 final int overscrollMode = getOverScrollMode(); 2984 if (overscrollMode == OVER_SCROLL_ALWAYS || 2985 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && 2986 !contentFits())) { 2987 if (rawDeltaY > 0) { 2988 mEdgeGlowTop.onPull((float) -incrementalDeltaY / getHeight()); 2989 if (!mEdgeGlowBottom.isFinished()) { 2990 mEdgeGlowBottom.onRelease(); 2991 } 2992 } else if (rawDeltaY < 0) { 2993 mEdgeGlowBottom.onPull((float) -incrementalDeltaY / getHeight()); 2994 if (!mEdgeGlowTop.isFinished()) { 2995 mEdgeGlowTop.onRelease(); 2996 } 2997 } 2998 invalidate(); 2999 } 3000 if (Math.abs(mOverscrollDistance) == Math.abs(mScrollY)) { 3001 // Don't allow overfling if we're at the edge. 3002 mVelocityTracker.clear(); 3003 } 3004 } 3005 mLastY = y; 3006 mDirection = newDirection; 3007 } 3008 break; 3009 } 3010 3011 break; 3012 } 3013 3014 case MotionEvent.ACTION_UP: { 3015 switch (mTouchMode) { 3016 case TOUCH_MODE_DOWN: 3017 case TOUCH_MODE_TAP: 3018 case TOUCH_MODE_DONE_WAITING: 3019 final int motionPosition = mMotionPosition; 3020 final View child = getChildAt(motionPosition - mFirstPosition); 3021 if (child != null && !child.hasFocusable()) { 3022 if (mTouchMode != TOUCH_MODE_DOWN) { 3023 child.setPressed(false); 3024 } 3025 3026 if (mPerformClick == null) { 3027 mPerformClick = new PerformClick(); 3028 } 3029 3030 final AbsListView.PerformClick performClick = mPerformClick; 3031 performClick.mClickMotionPosition = motionPosition; 3032 performClick.rememberWindowAttachCount(); 3033 3034 mResurrectToPosition = motionPosition; 3035 3036 if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) { 3037 final Handler handler = getHandler(); 3038 if (handler != null) { 3039 handler.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ? 3040 mPendingCheckForTap : mPendingCheckForLongPress); 3041 } 3042 mLayoutMode = LAYOUT_NORMAL; 3043 if (!mDataChanged && mAdapter.isEnabled(motionPosition)) { 3044 mTouchMode = TOUCH_MODE_TAP; 3045 setSelectedPositionInt(mMotionPosition); 3046 layoutChildren(); 3047 child.setPressed(true); 3048 positionSelector(mMotionPosition, child); 3049 setPressed(true); 3050 if (mSelector != null) { 3051 Drawable d = mSelector.getCurrent(); 3052 if (d != null && d instanceof TransitionDrawable) { 3053 ((TransitionDrawable) d).resetTransition(); 3054 } 3055 } 3056 if (mTouchModeReset != null) { 3057 removeCallbacks(mTouchModeReset); 3058 } 3059 mTouchModeReset = new Runnable() { 3060 @Override 3061 public void run() { 3062 mTouchMode = TOUCH_MODE_REST; 3063 child.setPressed(false); 3064 setPressed(false); 3065 if (!mDataChanged) { 3066 performClick.run(); 3067 } 3068 } 3069 }; 3070 postDelayed(mTouchModeReset, 3071 ViewConfiguration.getPressedStateDuration()); 3072 } else { 3073 mTouchMode = TOUCH_MODE_REST; 3074 updateSelectorState(); 3075 } 3076 return true; 3077 } else if (!mDataChanged && mAdapter.isEnabled(motionPosition)) { 3078 performClick.run(); 3079 } 3080 } 3081 mTouchMode = TOUCH_MODE_REST; 3082 updateSelectorState(); 3083 break; 3084 case TOUCH_MODE_SCROLL: 3085 final int childCount = getChildCount(); 3086 if (childCount > 0) { 3087 final int firstChildTop = getChildAt(0).getTop(); 3088 final int lastChildBottom = getChildAt(childCount - 1).getBottom(); 3089 final int contentTop = mListPadding.top; 3090 final int contentBottom = getHeight() - mListPadding.bottom; 3091 if (mFirstPosition == 0 && firstChildTop >= contentTop && 3092 mFirstPosition + childCount < mItemCount && 3093 lastChildBottom <= getHeight() - contentBottom) { 3094 mTouchMode = TOUCH_MODE_REST; 3095 reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 3096 } else { 3097 final VelocityTracker velocityTracker = mVelocityTracker; 3098 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 3099 3100 final int initialVelocity = (int) 3101 (velocityTracker.getYVelocity(mActivePointerId) * mVelocityScale); 3102 // Fling if we have enough velocity and we aren't at a boundary. 3103 // Since we can potentially overfling more than we can overscroll, don't 3104 // allow the weird behavior where you can scroll to a boundary then 3105 // fling further. 3106 if (Math.abs(initialVelocity) > mMinimumVelocity && 3107 !((mFirstPosition == 0 && 3108 firstChildTop == contentTop - mOverscrollDistance) || 3109 (mFirstPosition + childCount == mItemCount && 3110 lastChildBottom == contentBottom + mOverscrollDistance))) { 3111 if (mFlingRunnable == null) { 3112 mFlingRunnable = new FlingRunnable(); 3113 } 3114 reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING); 3115 3116 mFlingRunnable.start(-initialVelocity); 3117 } else { 3118 mTouchMode = TOUCH_MODE_REST; 3119 reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 3120 if (mFlingRunnable != null) { 3121 mFlingRunnable.endFling(); 3122 } 3123 if (mPositionScroller != null) { 3124 mPositionScroller.stop(); 3125 } 3126 } 3127 } 3128 } else { 3129 mTouchMode = TOUCH_MODE_REST; 3130 reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 3131 } 3132 break; 3133 3134 case TOUCH_MODE_OVERSCROLL: 3135 if (mFlingRunnable == null) { 3136 mFlingRunnable = new FlingRunnable(); 3137 } 3138 final VelocityTracker velocityTracker = mVelocityTracker; 3139 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 3140 final int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId); 3141 3142 reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING); 3143 if (Math.abs(initialVelocity) > mMinimumVelocity) { 3144 mFlingRunnable.startOverfling(-initialVelocity); 3145 } else { 3146 mFlingRunnable.startSpringback(); 3147 } 3148 3149 break; 3150 } 3151 3152 setPressed(false); 3153 3154 if (mEdgeGlowTop != null) { 3155 mEdgeGlowTop.onRelease(); 3156 mEdgeGlowBottom.onRelease(); 3157 } 3158 3159 // Need to redraw since we probably aren't drawing the selector anymore 3160 invalidate(); 3161 3162 final Handler handler = getHandler(); 3163 if (handler != null) { 3164 handler.removeCallbacks(mPendingCheckForLongPress); 3165 } 3166 3167 if (mVelocityTracker != null) { 3168 mVelocityTracker.recycle(); 3169 mVelocityTracker = null; 3170 } 3171 3172 mActivePointerId = INVALID_POINTER; 3173 3174 if (PROFILE_SCROLLING) { 3175 if (mScrollProfilingStarted) { 3176 Debug.stopMethodTracing(); 3177 mScrollProfilingStarted = false; 3178 } 3179 } 3180 3181 if (mScrollStrictSpan != null) { 3182 mScrollStrictSpan.finish(); 3183 mScrollStrictSpan = null; 3184 } 3185 break; 3186 } 3187 3188 case MotionEvent.ACTION_CANCEL: { 3189 switch (mTouchMode) { 3190 case TOUCH_MODE_OVERSCROLL: 3191 if (mFlingRunnable == null) { 3192 mFlingRunnable = new FlingRunnable(); 3193 } 3194 mFlingRunnable.startSpringback(); 3195 break; 3196 3197 case TOUCH_MODE_OVERFLING: 3198 // Do nothing - let it play out. 3199 break; 3200 3201 default: 3202 mTouchMode = TOUCH_MODE_REST; 3203 setPressed(false); 3204 View motionView = this.getChildAt(mMotionPosition - mFirstPosition); 3205 if (motionView != null) { 3206 motionView.setPressed(false); 3207 } 3208 clearScrollingCache(); 3209 3210 final Handler handler = getHandler(); 3211 if (handler != null) { 3212 handler.removeCallbacks(mPendingCheckForLongPress); 3213 } 3214 3215 if (mVelocityTracker != null) { 3216 mVelocityTracker.recycle(); 3217 mVelocityTracker = null; 3218 } 3219 } 3220 3221 if (mEdgeGlowTop != null) { 3222 mEdgeGlowTop.onRelease(); 3223 mEdgeGlowBottom.onRelease(); 3224 } 3225 mActivePointerId = INVALID_POINTER; 3226 break; 3227 } 3228 3229 case MotionEvent.ACTION_POINTER_UP: { 3230 onSecondaryPointerUp(ev); 3231 final int x = mMotionX; 3232 final int y = mMotionY; 3233 final int motionPosition = pointToPosition(x, y); 3234 if (motionPosition >= 0) { 3235 // Remember where the motion event started 3236 v = getChildAt(motionPosition - mFirstPosition); 3237 mMotionViewOriginalTop = v.getTop(); 3238 mMotionPosition = motionPosition; 3239 } 3240 mLastY = y; 3241 break; 3242 } 3243 } 3244 3245 return true; 3246 } 3247 3248 @Override 3249 protected void onOverScrolled(int scrollX, int scrollY, 3250 boolean clampedX, boolean clampedY) { 3251 mScrollY = scrollY; 3252 invalidateParentIfNeeded(); 3253 3254 if (clampedY) { 3255 // Velocity is broken by hitting the limit; don't start a fling off of this. 3256 if (mVelocityTracker != null) { 3257 mVelocityTracker.clear(); 3258 } 3259 } 3260 awakenScrollBars(); 3261 } 3262 3263 @Override 3264 public void draw(Canvas canvas) { 3265 super.draw(canvas); 3266 if (mEdgeGlowTop != null) { 3267 final int scrollY = mScrollY; 3268 if (!mEdgeGlowTop.isFinished()) { 3269 final int restoreCount = canvas.save(); 3270 final int width = getWidth(); 3271 3272 canvas.translate(0, Math.min(0, scrollY + mFirstPositionDistanceGuess)); 3273 mEdgeGlowTop.setSize(width, getHeight()); 3274 if (mEdgeGlowTop.draw(canvas)) { 3275 invalidate(); 3276 } 3277 canvas.restoreToCount(restoreCount); 3278 } 3279 if (!mEdgeGlowBottom.isFinished()) { 3280 final int restoreCount = canvas.save(); 3281 final int width = getWidth(); 3282 final int height = getHeight(); 3283 3284 canvas.translate(-width, Math.max(height, scrollY + mLastPositionDistanceGuess)); 3285 canvas.rotate(180, width, 0); 3286 mEdgeGlowBottom.setSize(width, height); 3287 if (mEdgeGlowBottom.draw(canvas)) { 3288 invalidate(); 3289 } 3290 canvas.restoreToCount(restoreCount); 3291 } 3292 } 3293 if (mFastScroller != null) { 3294 final int scrollY = mScrollY; 3295 if (scrollY != 0) { 3296 // Pin to the top/bottom during overscroll 3297 int restoreCount = canvas.save(); 3298 canvas.translate(0, (float) scrollY); 3299 mFastScroller.draw(canvas); 3300 canvas.restoreToCount(restoreCount); 3301 } else { 3302 mFastScroller.draw(canvas); 3303 } 3304 } 3305 } 3306 3307 @Override 3308 public boolean onInterceptTouchEvent(MotionEvent ev) { 3309 int action = ev.getAction(); 3310 View v; 3311 3312 if (mFastScroller != null) { 3313 boolean intercepted = mFastScroller.onInterceptTouchEvent(ev); 3314 if (intercepted) { 3315 return true; 3316 } 3317 } 3318 3319 switch (action & MotionEvent.ACTION_MASK) { 3320 case MotionEvent.ACTION_DOWN: { 3321 int touchMode = mTouchMode; 3322 if (touchMode == TOUCH_MODE_OVERFLING || touchMode == TOUCH_MODE_OVERSCROLL) { 3323 mMotionCorrection = 0; 3324 return true; 3325 } 3326 3327 final int x = (int) ev.getX(); 3328 final int y = (int) ev.getY(); 3329 mActivePointerId = ev.getPointerId(0); 3330 3331 int motionPosition = findMotionRow(y); 3332 if (touchMode != TOUCH_MODE_FLING && motionPosition >= 0) { 3333 // User clicked on an actual view (and was not stopping a fling). 3334 // Remember where the motion event started 3335 v = getChildAt(motionPosition - mFirstPosition); 3336 mMotionViewOriginalTop = v.getTop(); 3337 mMotionX = x; 3338 mMotionY = y; 3339 mMotionPosition = motionPosition; 3340 mTouchMode = TOUCH_MODE_DOWN; 3341 clearScrollingCache(); 3342 } 3343 mLastY = Integer.MIN_VALUE; 3344 if (touchMode == TOUCH_MODE_FLING) { 3345 return true; 3346 } 3347 break; 3348 } 3349 3350 case MotionEvent.ACTION_MOVE: { 3351 switch (mTouchMode) { 3352 case TOUCH_MODE_DOWN: 3353 final int pointerIndex = ev.findPointerIndex(mActivePointerId); 3354 final int y = (int) ev.getY(pointerIndex); 3355 if (startScrollIfNeeded(y - mMotionY)) { 3356 return true; 3357 } 3358 break; 3359 } 3360 break; 3361 } 3362 3363 case MotionEvent.ACTION_UP: { 3364 mTouchMode = TOUCH_MODE_REST; 3365 mActivePointerId = INVALID_POINTER; 3366 reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 3367 break; 3368 } 3369 3370 case MotionEvent.ACTION_POINTER_UP: { 3371 onSecondaryPointerUp(ev); 3372 break; 3373 } 3374 } 3375 3376 return false; 3377 } 3378 3379 private void onSecondaryPointerUp(MotionEvent ev) { 3380 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> 3381 MotionEvent.ACTION_POINTER_INDEX_SHIFT; 3382 final int pointerId = ev.getPointerId(pointerIndex); 3383 if (pointerId == mActivePointerId) { 3384 // This was our active pointer going up. Choose a new 3385 // active pointer and adjust accordingly. 3386 // TODO: Make this decision more intelligent. 3387 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 3388 mMotionX = (int) ev.getX(newPointerIndex); 3389 mMotionY = (int) ev.getY(newPointerIndex); 3390 mMotionCorrection = 0; 3391 mActivePointerId = ev.getPointerId(newPointerIndex); 3392 if (mVelocityTracker != null) { 3393 mVelocityTracker.clear(); 3394 } 3395 } 3396 } 3397 3398 /** 3399 * {@inheritDoc} 3400 */ 3401 @Override 3402 public void addTouchables(ArrayList<View> views) { 3403 final int count = getChildCount(); 3404 final int firstPosition = mFirstPosition; 3405 final ListAdapter adapter = mAdapter; 3406 3407 if (adapter == null) { 3408 return; 3409 } 3410 3411 for (int i = 0; i < count; i++) { 3412 final View child = getChildAt(i); 3413 if (adapter.isEnabled(firstPosition + i)) { 3414 views.add(child); 3415 } 3416 child.addTouchables(views); 3417 } 3418 } 3419 3420 /** 3421 * Fires an "on scroll state changed" event to the registered 3422 * {@link android.widget.AbsListView.OnScrollListener}, if any. The state change 3423 * is fired only if the specified state is different from the previously known state. 3424 * 3425 * @param newState The new scroll state. 3426 */ 3427 void reportScrollStateChange(int newState) { 3428 if (newState != mLastScrollState) { 3429 if (mOnScrollListener != null) { 3430 mLastScrollState = newState; 3431 mOnScrollListener.onScrollStateChanged(this, newState); 3432 } 3433 } 3434 } 3435 3436 /** 3437 * Responsible for fling behavior. Use {@link #start(int)} to 3438 * initiate a fling. Each frame of the fling is handled in {@link #run()}. 3439 * A FlingRunnable will keep re-posting itself until the fling is done. 3440 * 3441 */ 3442 private class FlingRunnable implements Runnable { 3443 /** 3444 * Tracks the decay of a fling scroll 3445 */ 3446 private final OverScroller mScroller; 3447 3448 /** 3449 * Y value reported by mScroller on the previous fling 3450 */ 3451 private int mLastFlingY; 3452 3453 private final Runnable mCheckFlywheel = new Runnable() { 3454 public void run() { 3455 final int activeId = mActivePointerId; 3456 final VelocityTracker vt = mVelocityTracker; 3457 final OverScroller scroller = mScroller; 3458 if (vt == null || activeId == INVALID_POINTER) { 3459 return; 3460 } 3461 3462 vt.computeCurrentVelocity(1000, mMaximumVelocity); 3463 final float yvel = -vt.getYVelocity(activeId); 3464 3465 if (scroller.isScrollingInDirection(0, yvel)) { 3466 // Keep the fling alive a little longer 3467 postDelayed(this, FLYWHEEL_TIMEOUT); 3468 } else { 3469 endFling(); 3470 mTouchMode = TOUCH_MODE_SCROLL; 3471 reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); 3472 } 3473 } 3474 }; 3475 3476 private static final int FLYWHEEL_TIMEOUT = 40; // milliseconds 3477 3478 FlingRunnable() { 3479 mScroller = new OverScroller(getContext()); 3480 } 3481 3482 void start(int initialVelocity) { 3483 int initialY = initialVelocity < 0 ? Integer.MAX_VALUE : 0; 3484 mLastFlingY = initialY; 3485 mScroller.fling(0, initialY, 0, initialVelocity, 3486 0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE); 3487 mTouchMode = TOUCH_MODE_FLING; 3488 post(this); 3489 3490 if (PROFILE_FLINGING) { 3491 if (!mFlingProfilingStarted) { 3492 Debug.startMethodTracing("AbsListViewFling"); 3493 mFlingProfilingStarted = true; 3494 } 3495 } 3496 3497 if (mFlingStrictSpan == null) { 3498 mFlingStrictSpan = StrictMode.enterCriticalSpan("AbsListView-fling"); 3499 } 3500 } 3501 3502 void startSpringback() { 3503 if (mScroller.springBack(0, mScrollY, 0, 0, 0, 0)) { 3504 mTouchMode = TOUCH_MODE_OVERFLING; 3505 invalidate(); 3506 post(this); 3507 } else { 3508 mTouchMode = TOUCH_MODE_REST; 3509 } 3510 } 3511 3512 void startOverfling(int initialVelocity) { 3513 final int min = mScrollY > 0 ? Integer.MIN_VALUE : 0; 3514 final int max = mScrollY > 0 ? 0 : Integer.MAX_VALUE; 3515 mScroller.fling(0, mScrollY, 0, initialVelocity, 0, 0, min, max, 0, getHeight()); 3516 mTouchMode = TOUCH_MODE_OVERFLING; 3517 invalidate(); 3518 post(this); 3519 } 3520 3521 void edgeReached(int delta) { 3522 mScroller.notifyVerticalEdgeReached(mScrollY, 0, mOverflingDistance); 3523 final int overscrollMode = getOverScrollMode(); 3524 if (overscrollMode == OVER_SCROLL_ALWAYS || 3525 (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && !contentFits())) { 3526 mTouchMode = TOUCH_MODE_OVERFLING; 3527 final int vel = (int) mScroller.getCurrVelocity(); 3528 if (delta > 0) { 3529 mEdgeGlowTop.onAbsorb(vel); 3530 } else { 3531 mEdgeGlowBottom.onAbsorb(vel); 3532 } 3533 } else { 3534 mTouchMode = TOUCH_MODE_REST; 3535 if (mPositionScroller != null) { 3536 mPositionScroller.stop(); 3537 } 3538 } 3539 invalidate(); 3540 post(this); 3541 } 3542 3543 void startScroll(int distance, int duration) { 3544 int initialY = distance < 0 ? Integer.MAX_VALUE : 0; 3545 mLastFlingY = initialY; 3546 mScroller.startScroll(0, initialY, 0, distance, duration); 3547 mTouchMode = TOUCH_MODE_FLING; 3548 post(this); 3549 } 3550 3551 void endFling() { 3552 mTouchMode = TOUCH_MODE_REST; 3553 3554 removeCallbacks(this); 3555 removeCallbacks(mCheckFlywheel); 3556 3557 reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 3558 clearScrollingCache(); 3559 mScroller.abortAnimation(); 3560 3561 if (mFlingStrictSpan != null) { 3562 mFlingStrictSpan.finish(); 3563 mFlingStrictSpan = null; 3564 } 3565 } 3566 3567 void flywheelTouch() { 3568 postDelayed(mCheckFlywheel, FLYWHEEL_TIMEOUT); 3569 } 3570 3571 public void run() { 3572 switch (mTouchMode) { 3573 default: 3574 endFling(); 3575 return; 3576 3577 case TOUCH_MODE_SCROLL: 3578 if (mScroller.isFinished()) { 3579 return; 3580 } 3581 // Fall through 3582 case TOUCH_MODE_FLING: { 3583 if (mItemCount == 0 || getChildCount() == 0) { 3584 endFling(); 3585 return; 3586 } 3587 3588 final OverScroller scroller = mScroller; 3589 boolean more = scroller.computeScrollOffset(); 3590 final int y = scroller.getCurrY(); 3591 3592 // Flip sign to convert finger direction to list items direction 3593 // (e.g. finger moving down means list is moving towards the top) 3594 int delta = mLastFlingY - y; 3595 3596 // Pretend that each frame of a fling scroll is a touch scroll 3597 if (delta > 0) { 3598 // List is moving towards the top. Use first view as mMotionPosition 3599 mMotionPosition = mFirstPosition; 3600 final View firstView = getChildAt(0); 3601 mMotionViewOriginalTop = firstView.getTop(); 3602 3603 // Don't fling more than 1 screen 3604 delta = Math.min(getHeight() - mPaddingBottom - mPaddingTop - 1, delta); 3605 } else { 3606 // List is moving towards the bottom. Use last view as mMotionPosition 3607 int offsetToLast = getChildCount() - 1; 3608 mMotionPosition = mFirstPosition + offsetToLast; 3609 3610 final View lastView = getChildAt(offsetToLast); 3611 mMotionViewOriginalTop = lastView.getTop(); 3612 3613 // Don't fling more than 1 screen 3614 delta = Math.max(-(getHeight() - mPaddingBottom - mPaddingTop - 1), delta); 3615 } 3616 3617 // Check to see if we have bumped into the scroll limit 3618 View motionView = getChildAt(mMotionPosition - mFirstPosition); 3619 int oldTop = 0; 3620 if (motionView != null) { 3621 oldTop = motionView.getTop(); 3622 } 3623 3624 // Don't stop just because delta is zero (it could have been rounded) 3625 final boolean atEnd = trackMotionScroll(delta, delta) && (delta != 0); 3626 if (atEnd) { 3627 if (motionView != null) { 3628 // Tweak the scroll for how far we overshot 3629 int overshoot = -(delta - (motionView.getTop() - oldTop)); 3630 overScrollBy(0, overshoot, 0, mScrollY, 0, 0, 3631 0, mOverflingDistance, false); 3632 } 3633 if (more) { 3634 edgeReached(delta); 3635 } 3636 break; 3637 } 3638 3639 if (more && !atEnd) { 3640 invalidate(); 3641 mLastFlingY = y; 3642 post(this); 3643 } else { 3644 endFling(); 3645 3646 if (PROFILE_FLINGING) { 3647 if (mFlingProfilingStarted) { 3648 Debug.stopMethodTracing(); 3649 mFlingProfilingStarted = false; 3650 } 3651 3652 if (mFlingStrictSpan != null) { 3653 mFlingStrictSpan.finish(); 3654 mFlingStrictSpan = null; 3655 } 3656 } 3657 } 3658 break; 3659 } 3660 3661 case TOUCH_MODE_OVERFLING: { 3662 final OverScroller scroller = mScroller; 3663 if (scroller.computeScrollOffset()) { 3664 final int scrollY = mScrollY; 3665 final int deltaY = scroller.getCurrY() - scrollY; 3666 if (overScrollBy(0, deltaY, 0, scrollY, 0, 0, 3667 0, mOverflingDistance, false)) { 3668 startSpringback(); 3669 } else { 3670 invalidate(); 3671 post(this); 3672 } 3673 } else { 3674 endFling(); 3675 } 3676 break; 3677 } 3678 } 3679 } 3680 } 3681 3682 3683 class PositionScroller implements Runnable { 3684 private static final int SCROLL_DURATION = 400; 3685 3686 private static final int MOVE_DOWN_POS = 1; 3687 private static final int MOVE_UP_POS = 2; 3688 private static final int MOVE_DOWN_BOUND = 3; 3689 private static final int MOVE_UP_BOUND = 4; 3690 private static final int MOVE_OFFSET = 5; 3691 3692 private int mMode; 3693 private int mTargetPos; 3694 private int mBoundPos; 3695 private int mLastSeenPos; 3696 private int mScrollDuration; 3697 private final int mExtraScroll; 3698 3699 private int mOffsetFromTop; 3700 3701 PositionScroller() { 3702 mExtraScroll = ViewConfiguration.get(mContext).getScaledFadingEdgeLength(); 3703 } 3704 3705 void start(int position) { 3706 stop(); 3707 3708 final int firstPos = mFirstPosition; 3709 final int lastPos = firstPos + getChildCount() - 1; 3710 3711 int viewTravelCount; 3712 if (position <= firstPos) { 3713 viewTravelCount = firstPos - position + 1; 3714 mMode = MOVE_UP_POS; 3715 } else if (position >= lastPos) { 3716 viewTravelCount = position - lastPos + 1; 3717 mMode = MOVE_DOWN_POS; 3718 } else { 3719 // Already on screen, nothing to do 3720 return; 3721 } 3722 3723 if (viewTravelCount > 0) { 3724 mScrollDuration = SCROLL_DURATION / viewTravelCount; 3725 } else { 3726 mScrollDuration = SCROLL_DURATION; 3727 } 3728 mTargetPos = position; 3729 mBoundPos = INVALID_POSITION; 3730 mLastSeenPos = INVALID_POSITION; 3731 3732 post(this); 3733 } 3734 3735 void start(int position, int boundPosition) { 3736 stop(); 3737 3738 if (boundPosition == INVALID_POSITION) { 3739 start(position); 3740 return; 3741 } 3742 3743 final int firstPos = mFirstPosition; 3744 final int lastPos = firstPos + getChildCount() - 1; 3745 3746 int viewTravelCount; 3747 if (position <= firstPos) { 3748 final int boundPosFromLast = lastPos - boundPosition; 3749 if (boundPosFromLast < 1) { 3750 // Moving would shift our bound position off the screen. Abort. 3751 return; 3752 } 3753 3754 final int posTravel = firstPos - position + 1; 3755 final int boundTravel = boundPosFromLast - 1; 3756 if (boundTravel < posTravel) { 3757 viewTravelCount = boundTravel; 3758 mMode = MOVE_UP_BOUND; 3759 } else { 3760 viewTravelCount = posTravel; 3761 mMode = MOVE_UP_POS; 3762 } 3763 } else if (position >= lastPos) { 3764 final int boundPosFromFirst = boundPosition - firstPos; 3765 if (boundPosFromFirst < 1) { 3766 // Moving would shift our bound position off the screen. Abort. 3767 return; 3768 } 3769 3770 final int posTravel = position - lastPos + 1; 3771 final int boundTravel = boundPosFromFirst - 1; 3772 if (boundTravel < posTravel) { 3773 viewTravelCount = boundTravel; 3774 mMode = MOVE_DOWN_BOUND; 3775 } else { 3776 viewTravelCount = posTravel; 3777 mMode = MOVE_DOWN_POS; 3778 } 3779 } else { 3780 // Already on screen, nothing to do 3781 return; 3782 } 3783 3784 if (viewTravelCount > 0) { 3785 mScrollDuration = SCROLL_DURATION / viewTravelCount; 3786 } else { 3787 mScrollDuration = SCROLL_DURATION; 3788 } 3789 mTargetPos = position; 3790 mBoundPos = boundPosition; 3791 mLastSeenPos = INVALID_POSITION; 3792 3793 post(this); 3794 } 3795 3796 void startWithOffset(int position, int offset) { 3797 startWithOffset(position, offset, SCROLL_DURATION); 3798 } 3799 3800 void startWithOffset(int position, int offset, int duration) { 3801 stop(); 3802 3803 mTargetPos = position; 3804 mOffsetFromTop = offset; 3805 mBoundPos = INVALID_POSITION; 3806 mLastSeenPos = INVALID_POSITION; 3807 mMode = MOVE_OFFSET; 3808 3809 final int firstPos = mFirstPosition; 3810 final int childCount = getChildCount(); 3811 final int lastPos = firstPos + childCount - 1; 3812 3813 int viewTravelCount; 3814 if (position < firstPos) { 3815 viewTravelCount = firstPos - position; 3816 } else if (position > lastPos) { 3817 viewTravelCount = position - lastPos; 3818 } else { 3819 // On-screen, just scroll. 3820 final int targetTop = getChildAt(position - firstPos).getTop(); 3821 smoothScrollBy(targetTop - offset, duration); 3822 return; 3823 } 3824 3825 // Estimate how many screens we should travel 3826 final float screenTravelCount = (float) viewTravelCount / childCount; 3827 mScrollDuration = screenTravelCount < 1 ? (int) (screenTravelCount * duration) : 3828 (int) (duration / screenTravelCount); 3829 mLastSeenPos = INVALID_POSITION; 3830 3831 post(this); 3832 } 3833 3834 void stop() { 3835 removeCallbacks(this); 3836 } 3837 3838 public void run() { 3839 if (mTouchMode != TOUCH_MODE_FLING && mLastSeenPos != INVALID_POSITION) { 3840 return; 3841 } 3842 3843 final int listHeight = getHeight(); 3844 final int firstPos = mFirstPosition; 3845 3846 switch (mMode) { 3847 case MOVE_DOWN_POS: { 3848 final int lastViewIndex = getChildCount() - 1; 3849 final int lastPos = firstPos + lastViewIndex; 3850 3851 if (lastViewIndex < 0) { 3852 return; 3853 } 3854 3855 if (lastPos == mLastSeenPos) { 3856 // No new views, let things keep going. 3857 post(this); 3858 return; 3859 } 3860 3861 final View lastView = getChildAt(lastViewIndex); 3862 final int lastViewHeight = lastView.getHeight(); 3863 final int lastViewTop = lastView.getTop(); 3864 final int lastViewPixelsShowing = listHeight - lastViewTop; 3865 final int extraScroll = lastPos < mItemCount - 1 ? mExtraScroll : mListPadding.bottom; 3866 3867 smoothScrollBy(lastViewHeight - lastViewPixelsShowing + extraScroll, 3868 mScrollDuration); 3869 3870 mLastSeenPos = lastPos; 3871 if (lastPos < mTargetPos) { 3872 post(this); 3873 } 3874 break; 3875 } 3876 3877 case MOVE_DOWN_BOUND: { 3878 final int nextViewIndex = 1; 3879 final int childCount = getChildCount(); 3880 3881 if (firstPos == mBoundPos || childCount <= nextViewIndex 3882 || firstPos + childCount >= mItemCount) { 3883 return; 3884 } 3885 final int nextPos = firstPos + nextViewIndex; 3886 3887 if (nextPos == mLastSeenPos) { 3888 // No new views, let things keep going. 3889 post(this); 3890 return; 3891 } 3892 3893 final View nextView = getChildAt(nextViewIndex); 3894 final int nextViewHeight = nextView.getHeight(); 3895 final int nextViewTop = nextView.getTop(); 3896 final int extraScroll = mExtraScroll; 3897 if (nextPos < mBoundPos) { 3898 smoothScrollBy(Math.max(0, nextViewHeight + nextViewTop - extraScroll), 3899 mScrollDuration); 3900 3901 mLastSeenPos = nextPos; 3902 3903 post(this); 3904 } else { 3905 if (nextViewTop > extraScroll) { 3906 smoothScrollBy(nextViewTop - extraScroll, mScrollDuration); 3907 } 3908 } 3909 break; 3910 } 3911 3912 case MOVE_UP_POS: { 3913 if (firstPos == mLastSeenPos) { 3914 // No new views, let things keep going. 3915 post(this); 3916 return; 3917 } 3918 3919 final View firstView = getChildAt(0); 3920 if (firstView == null) { 3921 return; 3922 } 3923 final int firstViewTop = firstView.getTop(); 3924 final int extraScroll = firstPos > 0 ? mExtraScroll : mListPadding.top; 3925 3926 smoothScrollBy(firstViewTop - extraScroll, mScrollDuration); 3927 3928 mLastSeenPos = firstPos; 3929 3930 if (firstPos > mTargetPos) { 3931 post(this); 3932 } 3933 break; 3934 } 3935 3936 case MOVE_UP_BOUND: { 3937 final int lastViewIndex = getChildCount() - 2; 3938 if (lastViewIndex < 0) { 3939 return; 3940 } 3941 final int lastPos = firstPos + lastViewIndex; 3942 3943 if (lastPos == mLastSeenPos) { 3944 // No new views, let things keep going. 3945 post(this); 3946 return; 3947 } 3948 3949 final View lastView = getChildAt(lastViewIndex); 3950 final int lastViewHeight = lastView.getHeight(); 3951 final int lastViewTop = lastView.getTop(); 3952 final int lastViewPixelsShowing = listHeight - lastViewTop; 3953 mLastSeenPos = lastPos; 3954 if (lastPos > mBoundPos) { 3955 smoothScrollBy(-(lastViewPixelsShowing - mExtraScroll), mScrollDuration); 3956 post(this); 3957 } else { 3958 final int bottom = listHeight - mExtraScroll; 3959 final int lastViewBottom = lastViewTop + lastViewHeight; 3960 if (bottom > lastViewBottom) { 3961 smoothScrollBy(-(bottom - lastViewBottom), mScrollDuration); 3962 } 3963 } 3964 break; 3965 } 3966 3967 case MOVE_OFFSET: { 3968 if (mLastSeenPos == firstPos) { 3969 // No new views, let things keep going. 3970 post(this); 3971 return; 3972 } 3973 3974 mLastSeenPos = firstPos; 3975 3976 final int childCount = getChildCount(); 3977 final int position = mTargetPos; 3978 final int lastPos = firstPos + childCount - 1; 3979 3980 int viewTravelCount = 0; 3981 if (position < firstPos) { 3982 viewTravelCount = firstPos - position + 1; 3983 } else if (position > lastPos) { 3984 viewTravelCount = position - lastPos; 3985 } 3986 3987 // Estimate how many screens we should travel 3988 final float screenTravelCount = (float) viewTravelCount / childCount; 3989 3990 final float modifier = Math.min(Math.abs(screenTravelCount), 1.f); 3991 if (position < firstPos) { 3992 smoothScrollBy((int) (-getHeight() * modifier), mScrollDuration); 3993 post(this); 3994 } else if (position > lastPos) { 3995 smoothScrollBy((int) (getHeight() * modifier), mScrollDuration); 3996 post(this); 3997 } else { 3998 // On-screen, just scroll. 3999 final int targetTop = getChildAt(position - firstPos).getTop(); 4000 final int distance = targetTop - mOffsetFromTop; 4001 smoothScrollBy(distance, 4002 (int) (mScrollDuration * ((float) distance / getHeight()))); 4003 } 4004 break; 4005 } 4006 4007 default: 4008 break; 4009 } 4010 } 4011 } 4012 4013 /** 4014 * The amount of friction applied to flings. The default value 4015 * is {@link ViewConfiguration#getScrollFriction}. 4016 * 4017 * @return A scalar dimensionless value representing the coefficient of 4018 * friction. 4019 */ 4020 public void setFriction(float friction) { 4021 if (mFlingRunnable == null) { 4022 mFlingRunnable = new FlingRunnable(); 4023 } 4024 mFlingRunnable.mScroller.setFriction(friction); 4025 } 4026 4027 /** 4028 * Sets a scale factor for the fling velocity. The initial scale 4029 * factor is 1.0. 4030 * 4031 * @param scale The scale factor to multiply the velocity by. 4032 */ 4033 public void setVelocityScale(float scale) { 4034 mVelocityScale = scale; 4035 } 4036 4037 /** 4038 * Smoothly scroll to the specified adapter position. The view will 4039 * scroll such that the indicated position is displayed. 4040 * @param position Scroll to this adapter position. 4041 */ 4042 public void smoothScrollToPosition(int position) { 4043 if (mPositionScroller == null) { 4044 mPositionScroller = new PositionScroller(); 4045 } 4046 mPositionScroller.start(position); 4047 } 4048 4049 /** 4050 * Smoothly scroll to the specified adapter position. The view will scroll 4051 * such that the indicated position is displayed <code>offset</code> pixels from 4052 * the top edge of the view. If this is impossible, (e.g. the offset would scroll 4053 * the first or last item beyond the boundaries of the list) it will get as close 4054 * as possible. The scroll will take <code>duration</code> milliseconds to complete. 4055 * 4056 * @param position Position to scroll to 4057 * @param offset Desired distance in pixels of <code>position</code> from the top 4058 * of the view when scrolling is finished 4059 * @param duration Number of milliseconds to use for the scroll 4060 */ 4061 public void smoothScrollToPositionFromTop(int position, int offset, int duration) { 4062 if (mPositionScroller == null) { 4063 mPositionScroller = new PositionScroller(); 4064 } 4065 mPositionScroller.startWithOffset(position, offset, duration); 4066 } 4067 4068 /** 4069 * Smoothly scroll to the specified adapter position. The view will scroll 4070 * such that the indicated position is displayed <code>offset</code> pixels from 4071 * the top edge of the view. If this is impossible, (e.g. the offset would scroll 4072 * the first or last item beyond the boundaries of the list) it will get as close 4073 * as possible. 4074 * 4075 * @param position Position to scroll to 4076 * @param offset Desired distance in pixels of <code>position</code> from the top 4077 * of the view when scrolling is finished 4078 */ 4079 public void smoothScrollToPositionFromTop(int position, int offset) { 4080 if (mPositionScroller == null) { 4081 mPositionScroller = new PositionScroller(); 4082 } 4083 mPositionScroller.startWithOffset(position, offset); 4084 } 4085 4086 /** 4087 * Smoothly scroll to the specified adapter position. The view will 4088 * scroll such that the indicated position is displayed, but it will 4089 * stop early if scrolling further would scroll boundPosition out of 4090 * view. 4091 * @param position Scroll to this adapter position. 4092 * @param boundPosition Do not scroll if it would move this adapter 4093 * position out of view. 4094 */ 4095 public void smoothScrollToPosition(int position, int boundPosition) { 4096 if (mPositionScroller == null) { 4097 mPositionScroller = new PositionScroller(); 4098 } 4099 mPositionScroller.start(position, boundPosition); 4100 } 4101 4102 /** 4103 * Smoothly scroll by distance pixels over duration milliseconds. 4104 * @param distance Distance to scroll in pixels. 4105 * @param duration Duration of the scroll animation in milliseconds. 4106 */ 4107 public void smoothScrollBy(int distance, int duration) { 4108 if (mFlingRunnable == null) { 4109 mFlingRunnable = new FlingRunnable(); 4110 } 4111 4112 // No sense starting to scroll if we're not going anywhere 4113 final int firstPos = mFirstPosition; 4114 final int childCount = getChildCount(); 4115 final int lastPos = firstPos + childCount; 4116 final int topLimit = getPaddingTop(); 4117 final int bottomLimit = getHeight() - getPaddingBottom(); 4118 4119 if (distance == 0 || mItemCount == 0 || childCount == 0 || 4120 (firstPos == 0 && getChildAt(0).getTop() == topLimit && distance < 0) || 4121 (lastPos == mItemCount - 1 && 4122 getChildAt(childCount - 1).getBottom() == bottomLimit && distance > 0)) { 4123 mFlingRunnable.endFling(); 4124 if (mPositionScroller != null) { 4125 mPositionScroller.stop(); 4126 } 4127 } else { 4128 reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING); 4129 mFlingRunnable.startScroll(distance, duration); 4130 } 4131 } 4132 4133 /** 4134 * Allows RemoteViews to scroll relatively to a position. 4135 */ 4136 void smoothScrollByOffset(int position) { 4137 int index = -1; 4138 if (position < 0) { 4139 index = getFirstVisiblePosition(); 4140 } else if (position > 0) { 4141 index = getLastVisiblePosition(); 4142 } 4143 4144 if (index > -1) { 4145 View child = getChildAt(index - getFirstVisiblePosition()); 4146 if (child != null) { 4147 Rect visibleRect = new Rect(); 4148 if (child.getGlobalVisibleRect(visibleRect)) { 4149 // the child is partially visible 4150 int childRectArea = child.getWidth() * child.getHeight(); 4151 int visibleRectArea = visibleRect.width() * visibleRect.height(); 4152 float visibleArea = (visibleRectArea / (float) childRectArea); 4153 final float visibleThreshold = 0.75f; 4154 if ((position < 0) && (visibleArea < visibleThreshold)) { 4155 // the top index is not perceivably visible so offset 4156 // to account for showing that top index as well 4157 ++index; 4158 } else if ((position > 0) && (visibleArea < visibleThreshold)) { 4159 // the bottom index is not perceivably visible so offset 4160 // to account for showing that bottom index as well 4161 --index; 4162 } 4163 } 4164 smoothScrollToPosition(Math.max(0, Math.min(getCount(), index + position))); 4165 } 4166 } 4167 } 4168 4169 private void createScrollingCache() { 4170 if (mScrollingCacheEnabled && !mCachingStarted) { 4171 setChildrenDrawnWithCacheEnabled(true); 4172 setChildrenDrawingCacheEnabled(true); 4173 mCachingStarted = mCachingActive = true; 4174 } 4175 } 4176 4177 private void clearScrollingCache() { 4178 if (mClearScrollingCache == null) { 4179 mClearScrollingCache = new Runnable() { 4180 public void run() { 4181 if (mCachingStarted) { 4182 mCachingStarted = mCachingActive = false; 4183 setChildrenDrawnWithCacheEnabled(false); 4184 if ((mPersistentDrawingCache & PERSISTENT_SCROLLING_CACHE) == 0) { 4185 setChildrenDrawingCacheEnabled(false); 4186 } 4187 if (!isAlwaysDrawnWithCacheEnabled()) { 4188 invalidate(); 4189 } 4190 } 4191 } 4192 }; 4193 } 4194 post(mClearScrollingCache); 4195 } 4196 4197 /** 4198 * Track a motion scroll 4199 * 4200 * @param deltaY Amount to offset mMotionView. This is the accumulated delta since the motion 4201 * began. Positive numbers mean the user's finger is moving down the screen. 4202 * @param incrementalDeltaY Change in deltaY from the previous event. 4203 * @return true if we're already at the beginning/end of the list and have nothing to do. 4204 */ 4205 boolean trackMotionScroll(int deltaY, int incrementalDeltaY) { 4206 final int childCount = getChildCount(); 4207 if (childCount == 0) { 4208 return true; 4209 } 4210 4211 final int firstTop = getChildAt(0).getTop(); 4212 final int lastBottom = getChildAt(childCount - 1).getBottom(); 4213 4214 final Rect listPadding = mListPadding; 4215 4216 // "effective padding" In this case is the amount of padding that affects 4217 // how much space should not be filled by items. If we don't clip to padding 4218 // there is no effective padding. 4219 int effectivePaddingTop = 0; 4220 int effectivePaddingBottom = 0; 4221 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) { 4222 effectivePaddingTop = listPadding.top; 4223 effectivePaddingBottom = listPadding.bottom; 4224 } 4225 4226 // FIXME account for grid vertical spacing too? 4227 final int spaceAbove = effectivePaddingTop - firstTop; 4228 final int end = getHeight() - effectivePaddingBottom; 4229 final int spaceBelow = lastBottom - end; 4230 4231 final int height = getHeight() - mPaddingBottom - mPaddingTop; 4232 if (deltaY < 0) { 4233 deltaY = Math.max(-(height - 1), deltaY); 4234 } else { 4235 deltaY = Math.min(height - 1, deltaY); 4236 } 4237 4238 if (incrementalDeltaY < 0) { 4239 incrementalDeltaY = Math.max(-(height - 1), incrementalDeltaY); 4240 } else { 4241 incrementalDeltaY = Math.min(height - 1, incrementalDeltaY); 4242 } 4243 4244 final int firstPosition = mFirstPosition; 4245 4246 // Update our guesses for where the first and last views are 4247 if (firstPosition == 0) { 4248 mFirstPositionDistanceGuess = firstTop - listPadding.top; 4249 } else { 4250 mFirstPositionDistanceGuess += incrementalDeltaY; 4251 } 4252 if (firstPosition + childCount == mItemCount) { 4253 mLastPositionDistanceGuess = lastBottom + listPadding.bottom; 4254 } else { 4255 mLastPositionDistanceGuess += incrementalDeltaY; 4256 } 4257 4258 if (firstPosition == 0 && firstTop >= listPadding.top && incrementalDeltaY >= 0) { 4259 // Don't need to move views down if the top of the first position 4260 // is already visible 4261 return incrementalDeltaY != 0; 4262 } 4263 4264 if (firstPosition + childCount == mItemCount && 4265 lastBottom <= getHeight() - listPadding.bottom && 4266 incrementalDeltaY <= 0) { 4267 // Don't need to move views up if the bottom of the last position 4268 // is already visible 4269 return incrementalDeltaY != 0; 4270 } 4271 4272 final boolean down = incrementalDeltaY < 0; 4273 4274 final boolean inTouchMode = isInTouchMode(); 4275 if (inTouchMode) { 4276 hideSelector(); 4277 } 4278 4279 final int headerViewsCount = getHeaderViewsCount(); 4280 final int footerViewsStart = mItemCount - getFooterViewsCount(); 4281 4282 int start = 0; 4283 int count = 0; 4284 4285 if (down) { 4286 int top = -incrementalDeltaY; 4287 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) { 4288 top += listPadding.top; 4289 } 4290 for (int i = 0; i < childCount; i++) { 4291 final View child = getChildAt(i); 4292 if (child.getBottom() >= top) { 4293 break; 4294 } else { 4295 count++; 4296 int position = firstPosition + i; 4297 if (position >= headerViewsCount && position < footerViewsStart) { 4298 mRecycler.addScrapView(child, position); 4299 4300 if (ViewDebug.TRACE_RECYCLER) { 4301 ViewDebug.trace(child, 4302 ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, 4303 firstPosition + i, -1); 4304 } 4305 } 4306 } 4307 } 4308 } else { 4309 int bottom = getHeight() - incrementalDeltaY; 4310 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) { 4311 bottom -= listPadding.bottom; 4312 } 4313 for (int i = childCount - 1; i >= 0; i--) { 4314 final View child = getChildAt(i); 4315 if (child.getTop() <= bottom) { 4316 break; 4317 } else { 4318 start = i; 4319 count++; 4320 int position = firstPosition + i; 4321 if (position >= headerViewsCount && position < footerViewsStart) { 4322 mRecycler.addScrapView(child, position); 4323 4324 if (ViewDebug.TRACE_RECYCLER) { 4325 ViewDebug.trace(child, 4326 ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, 4327 firstPosition + i, -1); 4328 } 4329 } 4330 } 4331 } 4332 } 4333 4334 mMotionViewNewTop = mMotionViewOriginalTop + deltaY; 4335 4336 mBlockLayoutRequests = true; 4337 4338 if (count > 0) { 4339 detachViewsFromParent(start, count); 4340 } 4341 offsetChildrenTopAndBottom(incrementalDeltaY); 4342 4343 if (down) { 4344 mFirstPosition += count; 4345 } 4346 4347 invalidate(); 4348 4349 final int absIncrementalDeltaY = Math.abs(incrementalDeltaY); 4350 if (spaceAbove < absIncrementalDeltaY || spaceBelow < absIncrementalDeltaY) { 4351 fillGap(down); 4352 } 4353 4354 if (!inTouchMode && mSelectedPosition != INVALID_POSITION) { 4355 final int childIndex = mSelectedPosition - mFirstPosition; 4356 if (childIndex >= 0 && childIndex < getChildCount()) { 4357 positionSelector(mSelectedPosition, getChildAt(childIndex)); 4358 } 4359 } else if (mSelectorPosition != INVALID_POSITION) { 4360 final int childIndex = mSelectorPosition - mFirstPosition; 4361 if (childIndex >= 0 && childIndex < getChildCount()) { 4362 positionSelector(INVALID_POSITION, getChildAt(childIndex)); 4363 } 4364 } else { 4365 mSelectorRect.setEmpty(); 4366 } 4367 4368 mBlockLayoutRequests = false; 4369 4370 invokeOnItemScrollListener(); 4371 awakenScrollBars(); 4372 4373 return false; 4374 } 4375 4376 /** 4377 * Returns the number of header views in the list. Header views are special views 4378 * at the top of the list that should not be recycled during a layout. 4379 * 4380 * @return The number of header views, 0 in the default implementation. 4381 */ 4382 int getHeaderViewsCount() { 4383 return 0; 4384 } 4385 4386 /** 4387 * Returns the number of footer views in the list. Footer views are special views 4388 * at the bottom of the list that should not be recycled during a layout. 4389 * 4390 * @return The number of footer views, 0 in the default implementation. 4391 */ 4392 int getFooterViewsCount() { 4393 return 0; 4394 } 4395 4396 /** 4397 * Fills the gap left open by a touch-scroll. During a touch scroll, children that 4398 * remain on screen are shifted and the other ones are discarded. The role of this 4399 * method is to fill the gap thus created by performing a partial layout in the 4400 * empty space. 4401 * 4402 * @param down true if the scroll is going down, false if it is going up 4403 */ 4404 abstract void fillGap(boolean down); 4405 4406 void hideSelector() { 4407 if (mSelectedPosition != INVALID_POSITION) { 4408 if (mLayoutMode != LAYOUT_SPECIFIC) { 4409 mResurrectToPosition = mSelectedPosition; 4410 } 4411 if (mNextSelectedPosition >= 0 && mNextSelectedPosition != mSelectedPosition) { 4412 mResurrectToPosition = mNextSelectedPosition; 4413 } 4414 setSelectedPositionInt(INVALID_POSITION); 4415 setNextSelectedPositionInt(INVALID_POSITION); 4416 mSelectedTop = 0; 4417 mSelectorShowing = false; 4418 } 4419 } 4420 4421 /** 4422 * @return A position to select. First we try mSelectedPosition. If that has been clobbered by 4423 * entering touch mode, we then try mResurrectToPosition. Values are pinned to the range 4424 * of items available in the adapter 4425 */ 4426 int reconcileSelectedPosition() { 4427 int position = mSelectedPosition; 4428 if (position < 0) { 4429 position = mResurrectToPosition; 4430 } 4431 position = Math.max(0, position); 4432 position = Math.min(position, mItemCount - 1); 4433 return position; 4434 } 4435 4436 /** 4437 * Find the row closest to y. This row will be used as the motion row when scrolling 4438 * 4439 * @param y Where the user touched 4440 * @return The position of the first (or only) item in the row containing y 4441 */ 4442 abstract int findMotionRow(int y); 4443 4444 /** 4445 * Find the row closest to y. This row will be used as the motion row when scrolling. 4446 * 4447 * @param y Where the user touched 4448 * @return The position of the first (or only) item in the row closest to y 4449 */ 4450 int findClosestMotionRow(int y) { 4451 final int childCount = getChildCount(); 4452 if (childCount == 0) { 4453 return INVALID_POSITION; 4454 } 4455 4456 final int motionRow = findMotionRow(y); 4457 return motionRow != INVALID_POSITION ? motionRow : mFirstPosition + childCount - 1; 4458 } 4459 4460 /** 4461 * Causes all the views to be rebuilt and redrawn. 4462 */ 4463 public void invalidateViews() { 4464 mDataChanged = true; 4465 rememberSyncState(); 4466 requestLayout(); 4467 invalidate(); 4468 } 4469 4470 /** 4471 * If there is a selection returns false. 4472 * Otherwise resurrects the selection and returns true if resurrected. 4473 */ 4474 boolean resurrectSelectionIfNeeded() { 4475 if (mSelectedPosition < 0) { 4476 return resurrectSelection(); 4477 } 4478 return false; 4479 } 4480 4481 /** 4482 * Makes the item at the supplied position selected. 4483 * 4484 * @param position the position of the new selection 4485 */ 4486 abstract void setSelectionInt(int position); 4487 4488 /** 4489 * Attempt to bring the selection back if the user is switching from touch 4490 * to trackball mode 4491 * @return Whether selection was set to something. 4492 */ 4493 boolean resurrectSelection() { 4494 final int childCount = getChildCount(); 4495 4496 if (childCount <= 0) { 4497 return false; 4498 } 4499 4500 int selectedTop = 0; 4501 int selectedPos; 4502 int childrenTop = mListPadding.top; 4503 int childrenBottom = mBottom - mTop - mListPadding.bottom; 4504 final int firstPosition = mFirstPosition; 4505 final int toPosition = mResurrectToPosition; 4506 boolean down = true; 4507 4508 if (toPosition >= firstPosition && toPosition < firstPosition + childCount) { 4509 selectedPos = toPosition; 4510 4511 final View selected = getChildAt(selectedPos - mFirstPosition); 4512 selectedTop = selected.getTop(); 4513 int selectedBottom = selected.getBottom(); 4514 4515 // We are scrolled, don't get in the fade 4516 if (selectedTop < childrenTop) { 4517 selectedTop = childrenTop + getVerticalFadingEdgeLength(); 4518 } else if (selectedBottom > childrenBottom) { 4519 selectedTop = childrenBottom - selected.getMeasuredHeight() 4520 - getVerticalFadingEdgeLength(); 4521 } 4522 } else { 4523 if (toPosition < firstPosition) { 4524 // Default to selecting whatever is first 4525 selectedPos = firstPosition; 4526 for (int i = 0; i < childCount; i++) { 4527 final View v = getChildAt(i); 4528 final int top = v.getTop(); 4529 4530 if (i == 0) { 4531 // Remember the position of the first item 4532 selectedTop = top; 4533 // See if we are scrolled at all 4534 if (firstPosition > 0 || top < childrenTop) { 4535 // If we are scrolled, don't select anything that is 4536 // in the fade region 4537 childrenTop += getVerticalFadingEdgeLength(); 4538 } 4539 } 4540 if (top >= childrenTop) { 4541 // Found a view whose top is fully visisble 4542 selectedPos = firstPosition + i; 4543 selectedTop = top; 4544 break; 4545 } 4546 } 4547 } else { 4548 final int itemCount = mItemCount; 4549 down = false; 4550 selectedPos = firstPosition + childCount - 1; 4551 4552 for (int i = childCount - 1; i >= 0; i--) { 4553 final View v = getChildAt(i); 4554 final int top = v.getTop(); 4555 final int bottom = v.getBottom(); 4556 4557 if (i == childCount - 1) { 4558 selectedTop = top; 4559 if (firstPosition + childCount < itemCount || bottom > childrenBottom) { 4560 childrenBottom -= getVerticalFadingEdgeLength(); 4561 } 4562 } 4563 4564 if (bottom <= childrenBottom) { 4565 selectedPos = firstPosition + i; 4566 selectedTop = top; 4567 break; 4568 } 4569 } 4570 } 4571 } 4572 4573 mResurrectToPosition = INVALID_POSITION; 4574 removeCallbacks(mFlingRunnable); 4575 if (mPositionScroller != null) { 4576 mPositionScroller.stop(); 4577 } 4578 mTouchMode = TOUCH_MODE_REST; 4579 clearScrollingCache(); 4580 mSpecificTop = selectedTop; 4581 selectedPos = lookForSelectablePosition(selectedPos, down); 4582 if (selectedPos >= firstPosition && selectedPos <= getLastVisiblePosition()) { 4583 mLayoutMode = LAYOUT_SPECIFIC; 4584 setSelectionInt(selectedPos); 4585 invokeOnItemScrollListener(); 4586 } else { 4587 selectedPos = INVALID_POSITION; 4588 } 4589 reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 4590 4591 return selectedPos >= 0; 4592 } 4593 4594 @Override 4595 protected void handleDataChanged() { 4596 int count = mItemCount; 4597 if (count > 0) { 4598 4599 int newPos; 4600 4601 int selectablePos; 4602 4603 // Find the row we are supposed to sync to 4604 if (mNeedSync) { 4605 // Update this first, since setNextSelectedPositionInt inspects it 4606 mNeedSync = false; 4607 4608 if (mTranscriptMode == TRANSCRIPT_MODE_ALWAYS_SCROLL) { 4609 mLayoutMode = LAYOUT_FORCE_BOTTOM; 4610 return; 4611 } else if (mTranscriptMode == TRANSCRIPT_MODE_NORMAL) { 4612 if (mForceTranscriptScroll) { 4613 mForceTranscriptScroll = false; 4614 mLayoutMode = LAYOUT_FORCE_BOTTOM; 4615 return; 4616 } 4617 final int childCount = getChildCount(); 4618 final int listBottom = getBottom() - getPaddingBottom(); 4619 final View lastChild = getChildAt(childCount - 1); 4620 final int lastBottom = lastChild != null ? lastChild.getBottom() : listBottom; 4621 if (mFirstPosition + childCount >= mOldItemCount && lastBottom <= listBottom) { 4622 mLayoutMode = LAYOUT_FORCE_BOTTOM; 4623 return; 4624 } 4625 // Something new came in and we didn't scroll; give the user a clue that 4626 // there's something new. 4627 awakenScrollBars(); 4628 } 4629 4630 switch (mSyncMode) { 4631 case SYNC_SELECTED_POSITION: 4632 if (isInTouchMode()) { 4633 // We saved our state when not in touch mode. (We know this because 4634 // mSyncMode is SYNC_SELECTED_POSITION.) Now we are trying to 4635 // restore in touch mode. Just leave mSyncPosition as it is (possibly 4636 // adjusting if the available range changed) and return. 4637 mLayoutMode = LAYOUT_SYNC; 4638 mSyncPosition = Math.min(Math.max(0, mSyncPosition), count - 1); 4639 4640 return; 4641 } else { 4642 // See if we can find a position in the new data with the same 4643 // id as the old selection. This will change mSyncPosition. 4644 newPos = findSyncPosition(); 4645 if (newPos >= 0) { 4646 // Found it. Now verify that new selection is still selectable 4647 selectablePos = lookForSelectablePosition(newPos, true); 4648 if (selectablePos == newPos) { 4649 // Same row id is selected 4650 mSyncPosition = newPos; 4651 4652 if (mSyncHeight == getHeight()) { 4653 // If we are at the same height as when we saved state, try 4654 // to restore the scroll position too. 4655 mLayoutMode = LAYOUT_SYNC; 4656 } else { 4657 // We are not the same height as when the selection was saved, so 4658 // don't try to restore the exact position 4659 mLayoutMode = LAYOUT_SET_SELECTION; 4660 } 4661 4662 // Restore selection 4663 setNextSelectedPositionInt(newPos); 4664 return; 4665 } 4666 } 4667 } 4668 break; 4669 case SYNC_FIRST_POSITION: 4670 // Leave mSyncPosition as it is -- just pin to available range 4671 mLayoutMode = LAYOUT_SYNC; 4672 mSyncPosition = Math.min(Math.max(0, mSyncPosition), count - 1); 4673 4674 return; 4675 } 4676 } 4677 4678 if (!isInTouchMode()) { 4679 // We couldn't find matching data -- try to use the same position 4680 newPos = getSelectedItemPosition(); 4681 4682 // Pin position to the available range 4683 if (newPos >= count) { 4684 newPos = count - 1; 4685 } 4686 if (newPos < 0) { 4687 newPos = 0; 4688 } 4689 4690 // Make sure we select something selectable -- first look down 4691 selectablePos = lookForSelectablePosition(newPos, true); 4692 4693 if (selectablePos >= 0) { 4694 setNextSelectedPositionInt(selectablePos); 4695 return; 4696 } else { 4697 // Looking down didn't work -- try looking up 4698 selectablePos = lookForSelectablePosition(newPos, false); 4699 if (selectablePos >= 0) { 4700 setNextSelectedPositionInt(selectablePos); 4701 return; 4702 } 4703 } 4704 } else { 4705 4706 // We already know where we want to resurrect the selection 4707 if (mResurrectToPosition >= 0) { 4708 return; 4709 } 4710 } 4711 4712 } 4713 4714 // Nothing is selected. Give up and reset everything. 4715 mLayoutMode = mStackFromBottom ? LAYOUT_FORCE_BOTTOM : LAYOUT_FORCE_TOP; 4716 mSelectedPosition = INVALID_POSITION; 4717 mSelectedRowId = INVALID_ROW_ID; 4718 mNextSelectedPosition = INVALID_POSITION; 4719 mNextSelectedRowId = INVALID_ROW_ID; 4720 mNeedSync = false; 4721 mSelectorPosition = INVALID_POSITION; 4722 checkSelectionChanged(); 4723 } 4724 4725 @Override 4726 protected void onDisplayHint(int hint) { 4727 super.onDisplayHint(hint); 4728 switch (hint) { 4729 case INVISIBLE: 4730 if (mPopup != null && mPopup.isShowing()) { 4731 dismissPopup(); 4732 } 4733 break; 4734 case VISIBLE: 4735 if (mFiltered && mPopup != null && !mPopup.isShowing()) { 4736 showPopup(); 4737 } 4738 break; 4739 } 4740 mPopupHidden = hint == INVISIBLE; 4741 } 4742 4743 /** 4744 * Removes the filter window 4745 */ 4746 private void dismissPopup() { 4747 if (mPopup != null) { 4748 mPopup.dismiss(); 4749 } 4750 } 4751 4752 /** 4753 * Shows the filter window 4754 */ 4755 private void showPopup() { 4756 // Make sure we have a window before showing the popup 4757 if (getWindowVisibility() == View.VISIBLE) { 4758 createTextFilter(true); 4759 positionPopup(); 4760 // Make sure we get focus if we are showing the popup 4761 checkFocus(); 4762 } 4763 } 4764 4765 private void positionPopup() { 4766 int screenHeight = getResources().getDisplayMetrics().heightPixels; 4767 final int[] xy = new int[2]; 4768 getLocationOnScreen(xy); 4769 // TODO: The 20 below should come from the theme 4770 // TODO: And the gravity should be defined in the theme as well 4771 final int bottomGap = screenHeight - xy[1] - getHeight() + (int) (mDensityScale * 20); 4772 if (!mPopup.isShowing()) { 4773 mPopup.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 4774 xy[0], bottomGap); 4775 } else { 4776 mPopup.update(xy[0], bottomGap, -1, -1); 4777 } 4778 } 4779 4780 /** 4781 * What is the distance between the source and destination rectangles given the direction of 4782 * focus navigation between them? The direction basically helps figure out more quickly what is 4783 * self evident by the relationship between the rects... 4784 * 4785 * @param source the source rectangle 4786 * @param dest the destination rectangle 4787 * @param direction the direction 4788 * @return the distance between the rectangles 4789 */ 4790 static int getDistance(Rect source, Rect dest, int direction) { 4791 int sX, sY; // source x, y 4792 int dX, dY; // dest x, y 4793 switch (direction) { 4794 case View.FOCUS_RIGHT: 4795 sX = source.right; 4796 sY = source.top + source.height() / 2; 4797 dX = dest.left; 4798 dY = dest.top + dest.height() / 2; 4799 break; 4800 case View.FOCUS_DOWN: 4801 sX = source.left + source.width() / 2; 4802 sY = source.bottom; 4803 dX = dest.left + dest.width() / 2; 4804 dY = dest.top; 4805 break; 4806 case View.FOCUS_LEFT: 4807 sX = source.left; 4808 sY = source.top + source.height() / 2; 4809 dX = dest.right; 4810 dY = dest.top + dest.height() / 2; 4811 break; 4812 case View.FOCUS_UP: 4813 sX = source.left + source.width() / 2; 4814 sY = source.top; 4815 dX = dest.left + dest.width() / 2; 4816 dY = dest.bottom; 4817 break; 4818 case View.FOCUS_FORWARD: 4819 case View.FOCUS_BACKWARD: 4820 sX = source.right + source.width() / 2; 4821 sY = source.top + source.height() / 2; 4822 dX = dest.left + dest.width() / 2; 4823 dY = dest.top + dest.height() / 2; 4824 break; 4825 default: 4826 throw new IllegalArgumentException("direction must be one of " 4827 + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, " 4828 + "FOCUS_FORWARD, FOCUS_BACKWARD}."); 4829 } 4830 int deltaX = dX - sX; 4831 int deltaY = dY - sY; 4832 return deltaY * deltaY + deltaX * deltaX; 4833 } 4834 4835 @Override 4836 protected boolean isInFilterMode() { 4837 return mFiltered; 4838 } 4839 4840 /** 4841 * Sends a key to the text filter window 4842 * 4843 * @param keyCode The keycode for the event 4844 * @param event The actual key event 4845 * 4846 * @return True if the text filter handled the event, false otherwise. 4847 */ 4848 boolean sendToTextFilter(int keyCode, int count, KeyEvent event) { 4849 if (!acceptFilter()) { 4850 return false; 4851 } 4852 4853 boolean handled = false; 4854 boolean okToSend = true; 4855 switch (keyCode) { 4856 case KeyEvent.KEYCODE_DPAD_UP: 4857 case KeyEvent.KEYCODE_DPAD_DOWN: 4858 case KeyEvent.KEYCODE_DPAD_LEFT: 4859 case KeyEvent.KEYCODE_DPAD_RIGHT: 4860 case KeyEvent.KEYCODE_DPAD_CENTER: 4861 case KeyEvent.KEYCODE_ENTER: 4862 okToSend = false; 4863 break; 4864 case KeyEvent.KEYCODE_BACK: 4865 if (mFiltered && mPopup != null && mPopup.isShowing()) { 4866 if (event.getAction() == KeyEvent.ACTION_DOWN 4867 && event.getRepeatCount() == 0) { 4868 KeyEvent.DispatcherState state = getKeyDispatcherState(); 4869 if (state != null) { 4870 state.startTracking(event, this); 4871 } 4872 handled = true; 4873 } else if (event.getAction() == KeyEvent.ACTION_UP 4874 && event.isTracking() && !event.isCanceled()) { 4875 handled = true; 4876 mTextFilter.setText(""); 4877 } 4878 } 4879 okToSend = false; 4880 break; 4881 case KeyEvent.KEYCODE_SPACE: 4882 // Only send spaces once we are filtered 4883 okToSend = mFiltered; 4884 break; 4885 } 4886 4887 if (okToSend) { 4888 createTextFilter(true); 4889 4890 KeyEvent forwardEvent = event; 4891 if (forwardEvent.getRepeatCount() > 0) { 4892 forwardEvent = KeyEvent.changeTimeRepeat(event, event.getEventTime(), 0); 4893 } 4894 4895 int action = event.getAction(); 4896 switch (action) { 4897 case KeyEvent.ACTION_DOWN: 4898 handled = mTextFilter.onKeyDown(keyCode, forwardEvent); 4899 break; 4900 4901 case KeyEvent.ACTION_UP: 4902 handled = mTextFilter.onKeyUp(keyCode, forwardEvent); 4903 break; 4904 4905 case KeyEvent.ACTION_MULTIPLE: 4906 handled = mTextFilter.onKeyMultiple(keyCode, count, event); 4907 break; 4908 } 4909 } 4910 return handled; 4911 } 4912 4913 /** 4914 * Return an InputConnection for editing of the filter text. 4915 */ 4916 @Override 4917 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 4918 if (isTextFilterEnabled()) { 4919 // XXX we need to have the text filter created, so we can get an 4920 // InputConnection to proxy to. Unfortunately this means we pretty 4921 // much need to make it as soon as a list view gets focus. 4922 createTextFilter(false); 4923 if (mPublicInputConnection == null) { 4924 mDefInputConnection = new BaseInputConnection(this, false); 4925 mPublicInputConnection = new InputConnectionWrapper( 4926 mTextFilter.onCreateInputConnection(outAttrs), true) { 4927 @Override 4928 public boolean reportFullscreenMode(boolean enabled) { 4929 // Use our own input connection, since it is 4930 // the "real" one the IME is talking with. 4931 return mDefInputConnection.reportFullscreenMode(enabled); 4932 } 4933 4934 @Override 4935 public boolean performEditorAction(int editorAction) { 4936 // The editor is off in its own window; we need to be 4937 // the one that does this. 4938 if (editorAction == EditorInfo.IME_ACTION_DONE) { 4939 InputMethodManager imm = (InputMethodManager) 4940 getContext().getSystemService( 4941 Context.INPUT_METHOD_SERVICE); 4942 if (imm != null) { 4943 imm.hideSoftInputFromWindow(getWindowToken(), 0); 4944 } 4945 return true; 4946 } 4947 return false; 4948 } 4949 4950 @Override 4951 public boolean sendKeyEvent(KeyEvent event) { 4952 // Use our own input connection, since the filter 4953 // text view may not be shown in a window so has 4954 // no ViewRoot to dispatch events with. 4955 return mDefInputConnection.sendKeyEvent(event); 4956 } 4957 }; 4958 } 4959 outAttrs.inputType = EditorInfo.TYPE_CLASS_TEXT 4960 | EditorInfo.TYPE_TEXT_VARIATION_FILTER; 4961 outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE; 4962 return mPublicInputConnection; 4963 } 4964 return null; 4965 } 4966 4967 /** 4968 * For filtering we proxy an input connection to an internal text editor, 4969 * and this allows the proxying to happen. 4970 */ 4971 @Override 4972 public boolean checkInputConnectionProxy(View view) { 4973 return view == mTextFilter; 4974 } 4975 4976 /** 4977 * Creates the window for the text filter and populates it with an EditText field; 4978 * 4979 * @param animateEntrance true if the window should appear with an animation 4980 */ 4981 private void createTextFilter(boolean animateEntrance) { 4982 if (mPopup == null) { 4983 Context c = getContext(); 4984 PopupWindow p = new PopupWindow(c); 4985 LayoutInflater layoutInflater = (LayoutInflater) 4986 c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 4987 mTextFilter = (EditText) layoutInflater.inflate( 4988 com.android.internal.R.layout.typing_filter, null); 4989 // For some reason setting this as the "real" input type changes 4990 // the text view in some way that it doesn't work, and I don't 4991 // want to figure out why this is. 4992 mTextFilter.setRawInputType(EditorInfo.TYPE_CLASS_TEXT 4993 | EditorInfo.TYPE_TEXT_VARIATION_FILTER); 4994 mTextFilter.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); 4995 mTextFilter.addTextChangedListener(this); 4996 p.setFocusable(false); 4997 p.setTouchable(false); 4998 p.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 4999 p.setContentView(mTextFilter); 5000 p.setWidth(LayoutParams.WRAP_CONTENT); 5001 p.setHeight(LayoutParams.WRAP_CONTENT); 5002 p.setBackgroundDrawable(null); 5003 mPopup = p; 5004 getViewTreeObserver().addOnGlobalLayoutListener(this); 5005 mGlobalLayoutListenerAddedFilter = true; 5006 } 5007 if (animateEntrance) { 5008 mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilter); 5009 } else { 5010 mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilterRestore); 5011 } 5012 } 5013 5014 /** 5015 * Clear the text filter. 5016 */ 5017 public void clearTextFilter() { 5018 if (mFiltered) { 5019 mTextFilter.setText(""); 5020 mFiltered = false; 5021 if (mPopup != null && mPopup.isShowing()) { 5022 dismissPopup(); 5023 } 5024 } 5025 } 5026 5027 /** 5028 * Returns if the ListView currently has a text filter. 5029 */ 5030 public boolean hasTextFilter() { 5031 return mFiltered; 5032 } 5033 5034 public void onGlobalLayout() { 5035 if (isShown()) { 5036 // Show the popup if we are filtered 5037 if (mFiltered && mPopup != null && !mPopup.isShowing() && !mPopupHidden) { 5038 showPopup(); 5039 } 5040 } else { 5041 // Hide the popup when we are no longer visible 5042 if (mPopup != null && mPopup.isShowing()) { 5043 dismissPopup(); 5044 } 5045 } 5046 5047 } 5048 5049 /** 5050 * For our text watcher that is associated with the text filter. Does 5051 * nothing. 5052 */ 5053 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 5054 } 5055 5056 /** 5057 * For our text watcher that is associated with the text filter. Performs 5058 * the actual filtering as the text changes, and takes care of hiding and 5059 * showing the popup displaying the currently entered filter text. 5060 */ 5061 public void onTextChanged(CharSequence s, int start, int before, int count) { 5062 if (mPopup != null && isTextFilterEnabled()) { 5063 int length = s.length(); 5064 boolean showing = mPopup.isShowing(); 5065 if (!showing && length > 0) { 5066 // Show the filter popup if necessary 5067 showPopup(); 5068 mFiltered = true; 5069 } else if (showing && length == 0) { 5070 // Remove the filter popup if the user has cleared all text 5071 dismissPopup(); 5072 mFiltered = false; 5073 } 5074 if (mAdapter instanceof Filterable) { 5075 Filter f = ((Filterable) mAdapter).getFilter(); 5076 // Filter should not be null when we reach this part 5077 if (f != null) { 5078 f.filter(s, this); 5079 } else { 5080 throw new IllegalStateException("You cannot call onTextChanged with a non " 5081 + "filterable adapter"); 5082 } 5083 } 5084 } 5085 } 5086 5087 /** 5088 * For our text watcher that is associated with the text filter. Does 5089 * nothing. 5090 */ 5091 public void afterTextChanged(Editable s) { 5092 } 5093 5094 public void onFilterComplete(int count) { 5095 if (mSelectedPosition < 0 && count > 0) { 5096 mResurrectToPosition = INVALID_POSITION; 5097 resurrectSelection(); 5098 } 5099 } 5100 5101 @Override 5102 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 5103 return new LayoutParams(p); 5104 } 5105 5106 @Override 5107 public LayoutParams generateLayoutParams(AttributeSet attrs) { 5108 return new AbsListView.LayoutParams(getContext(), attrs); 5109 } 5110 5111 @Override 5112 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 5113 return p instanceof AbsListView.LayoutParams; 5114 } 5115 5116 /** 5117 * Puts the list or grid into transcript mode. In this mode the list or grid will always scroll 5118 * to the bottom to show new items. 5119 * 5120 * @param mode the transcript mode to set 5121 * 5122 * @see #TRANSCRIPT_MODE_DISABLED 5123 * @see #TRANSCRIPT_MODE_NORMAL 5124 * @see #TRANSCRIPT_MODE_ALWAYS_SCROLL 5125 */ 5126 public void setTranscriptMode(int mode) { 5127 mTranscriptMode = mode; 5128 } 5129 5130 /** 5131 * Returns the current transcript mode. 5132 * 5133 * @return {@link #TRANSCRIPT_MODE_DISABLED}, {@link #TRANSCRIPT_MODE_NORMAL} or 5134 * {@link #TRANSCRIPT_MODE_ALWAYS_SCROLL} 5135 */ 5136 public int getTranscriptMode() { 5137 return mTranscriptMode; 5138 } 5139 5140 @Override 5141 public int getSolidColor() { 5142 return mCacheColorHint; 5143 } 5144 5145 /** 5146 * When set to a non-zero value, the cache color hint indicates that this list is always drawn 5147 * on top of a solid, single-color, opaque background. 5148 * 5149 * Zero means that what's behind this object is translucent (non solid) or is not made of a 5150 * single color. This hint will not affect any existing background drawable set on this view ( 5151 * typically set via {@link #setBackgroundDrawable(Drawable)}). 5152 * 5153 * @param color The background color 5154 */ 5155 public void setCacheColorHint(int color) { 5156 if (color != mCacheColorHint) { 5157 mCacheColorHint = color; 5158 int count = getChildCount(); 5159 for (int i = 0; i < count; i++) { 5160 getChildAt(i).setDrawingCacheBackgroundColor(color); 5161 } 5162 mRecycler.setCacheColorHint(color); 5163 } 5164 } 5165 5166 /** 5167 * When set to a non-zero value, the cache color hint indicates that this list is always drawn 5168 * on top of a solid, single-color, opaque background 5169 * 5170 * @return The cache color hint 5171 */ 5172 public int getCacheColorHint() { 5173 return mCacheColorHint; 5174 } 5175 5176 /** 5177 * Move all views (excluding headers and footers) held by this AbsListView into the supplied 5178 * List. This includes views displayed on the screen as well as views stored in AbsListView's 5179 * internal view recycler. 5180 * 5181 * @param views A list into which to put the reclaimed views 5182 */ 5183 public void reclaimViews(List<View> views) { 5184 int childCount = getChildCount(); 5185 RecyclerListener listener = mRecycler.mRecyclerListener; 5186 5187 // Reclaim views on screen 5188 for (int i = 0; i < childCount; i++) { 5189 View child = getChildAt(i); 5190 AbsListView.LayoutParams lp = (AbsListView.LayoutParams) child.getLayoutParams(); 5191 // Don't reclaim header or footer views, or views that should be ignored 5192 if (lp != null && mRecycler.shouldRecycleViewType(lp.viewType)) { 5193 views.add(child); 5194 if (listener != null) { 5195 // Pretend they went through the scrap heap 5196 listener.onMovedToScrapHeap(child); 5197 } 5198 } 5199 } 5200 mRecycler.reclaimScrapViews(views); 5201 removeAllViewsInLayout(); 5202 } 5203 5204 /** 5205 * @hide 5206 */ 5207 @Override 5208 protected boolean onConsistencyCheck(int consistency) { 5209 boolean result = super.onConsistencyCheck(consistency); 5210 5211 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 5212 5213 if (checkLayout) { 5214 // The active recycler must be empty 5215 final View[] activeViews = mRecycler.mActiveViews; 5216 int count = activeViews.length; 5217 for (int i = 0; i < count; i++) { 5218 if (activeViews[i] != null) { 5219 result = false; 5220 Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 5221 "AbsListView " + this + " has a view in its active recycler: " + 5222 activeViews[i]); 5223 } 5224 } 5225 5226 // All views in the recycler must NOT be on screen and must NOT have a parent 5227 final ArrayList<View> scrap = mRecycler.mCurrentScrap; 5228 if (!checkScrap(scrap)) result = false; 5229 final ArrayList<View>[] scraps = mRecycler.mScrapViews; 5230 count = scraps.length; 5231 for (int i = 0; i < count; i++) { 5232 if (!checkScrap(scraps[i])) result = false; 5233 } 5234 } 5235 5236 return result; 5237 } 5238 5239 private boolean checkScrap(ArrayList<View> scrap) { 5240 if (scrap == null) return true; 5241 boolean result = true; 5242 5243 final int count = scrap.size(); 5244 for (int i = 0; i < count; i++) { 5245 final View view = scrap.get(i); 5246 if (view.getParent() != null) { 5247 result = false; 5248 Log.d(ViewDebug.CONSISTENCY_LOG_TAG, "AbsListView " + this + 5249 " has a view in its scrap heap still attached to a parent: " + view); 5250 } 5251 if (indexOfChild(view) >= 0) { 5252 result = false; 5253 Log.d(ViewDebug.CONSISTENCY_LOG_TAG, "AbsListView " + this + 5254 " has a view in its scrap heap that is also a direct child: " + view); 5255 } 5256 } 5257 5258 return result; 5259 } 5260 5261 private void finishGlows() { 5262 if (mEdgeGlowTop != null) { 5263 mEdgeGlowTop.finish(); 5264 mEdgeGlowBottom.finish(); 5265 } 5266 } 5267 5268 /** 5269 * Sets up this AbsListView to use a remote views adapter which connects to a RemoteViewsService 5270 * through the specified intent. 5271 * @param intent the intent used to identify the RemoteViewsService for the adapter to connect to. 5272 */ 5273 public void setRemoteViewsAdapter(Intent intent) { 5274 // Ensure that we don't already have a RemoteViewsAdapter that is bound to an existing 5275 // service handling the specified intent. 5276 if (mRemoteAdapter != null) { 5277 Intent.FilterComparison fcNew = new Intent.FilterComparison(intent); 5278 Intent.FilterComparison fcOld = new Intent.FilterComparison( 5279 mRemoteAdapter.getRemoteViewsServiceIntent()); 5280 if (fcNew.equals(fcOld)) { 5281 return; 5282 } 5283 } 5284 5285 // Otherwise, create a new RemoteViewsAdapter for binding 5286 mRemoteAdapter = new RemoteViewsAdapter(getContext(), intent, this); 5287 } 5288 5289 /** 5290 * Called back when the adapter connects to the RemoteViewsService. 5291 */ 5292 public boolean onRemoteAdapterConnected() { 5293 if (mRemoteAdapter != mAdapter) { 5294 setAdapter(mRemoteAdapter); 5295 return false; 5296 } else if (mRemoteAdapter != null) { 5297 mRemoteAdapter.superNotifyDataSetChanged(); 5298 return true; 5299 } 5300 return false; 5301 } 5302 5303 /** 5304 * Called back when the adapter disconnects from the RemoteViewsService. 5305 */ 5306 public void onRemoteAdapterDisconnected() { 5307 // If the remote adapter disconnects, we keep it around 5308 // since the currently displayed items are still cached. 5309 // Further, we want the service to eventually reconnect 5310 // when necessary, as triggered by this view requesting 5311 // items from the Adapter. 5312 } 5313 5314 /** 5315 * Sets the recycler listener to be notified whenever a View is set aside in 5316 * the recycler for later reuse. This listener can be used to free resources 5317 * associated to the View. 5318 * 5319 * @param listener The recycler listener to be notified of views set aside 5320 * in the recycler. 5321 * 5322 * @see android.widget.AbsListView.RecycleBin 5323 * @see android.widget.AbsListView.RecyclerListener 5324 */ 5325 public void setRecyclerListener(RecyclerListener listener) { 5326 mRecycler.mRecyclerListener = listener; 5327 } 5328 5329 class AdapterDataSetObserver extends AdapterView<ListAdapter>.AdapterDataSetObserver { 5330 @Override 5331 public void onChanged() { 5332 super.onChanged(); 5333 if (mFastScroller != null) { 5334 mFastScroller.onSectionsChanged(); 5335 } 5336 } 5337 5338 @Override 5339 public void onInvalidated() { 5340 super.onInvalidated(); 5341 if (mFastScroller != null) { 5342 mFastScroller.onSectionsChanged(); 5343 } 5344 } 5345 } 5346 5347 /** 5348 * A MultiChoiceModeListener receives events for {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL}. 5349 * It acts as the {@link ActionMode.Callback} for the selection mode and also receives 5350 * {@link #onItemCheckedStateChanged(ActionMode, int, long, boolean)} events when the user 5351 * selects and deselects list items. 5352 */ 5353 public interface MultiChoiceModeListener extends ActionMode.Callback { 5354 /** 5355 * Called when an item is checked or unchecked during selection mode. 5356 * 5357 * @param mode The {@link ActionMode} providing the selection mode 5358 * @param position Adapter position of the item that was checked or unchecked 5359 * @param id Adapter ID of the item that was checked or unchecked 5360 * @param checked <code>true</code> if the item is now checked, <code>false</code> 5361 * if the item is now unchecked. 5362 */ 5363 public void onItemCheckedStateChanged(ActionMode mode, 5364 int position, long id, boolean checked); 5365 } 5366 5367 class MultiChoiceModeWrapper implements MultiChoiceModeListener { 5368 private MultiChoiceModeListener mWrapped; 5369 5370 public void setWrapped(MultiChoiceModeListener wrapped) { 5371 mWrapped = wrapped; 5372 } 5373 5374 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 5375 if (mWrapped.onCreateActionMode(mode, menu)) { 5376 // Initialize checked graphic state? 5377 setLongClickable(false); 5378 return true; 5379 } 5380 return false; 5381 } 5382 5383 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 5384 return mWrapped.onPrepareActionMode(mode, menu); 5385 } 5386 5387 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 5388 return mWrapped.onActionItemClicked(mode, item); 5389 } 5390 5391 public void onDestroyActionMode(ActionMode mode) { 5392 mWrapped.onDestroyActionMode(mode); 5393 mChoiceActionMode = null; 5394 5395 // Ending selection mode means deselecting everything. 5396 clearChoices(); 5397 5398 mDataChanged = true; 5399 rememberSyncState(); 5400 requestLayout(); 5401 5402 setLongClickable(true); 5403 } 5404 5405 public void onItemCheckedStateChanged(ActionMode mode, 5406 int position, long id, boolean checked) { 5407 mWrapped.onItemCheckedStateChanged(mode, position, id, checked); 5408 5409 // If there are no items selected we no longer need the selection mode. 5410 if (getCheckedItemCount() == 0) { 5411 mode.finish(); 5412 } 5413 } 5414 } 5415 5416 /** 5417 * AbsListView extends LayoutParams to provide a place to hold the view type. 5418 */ 5419 public static class LayoutParams extends ViewGroup.LayoutParams { 5420 /** 5421 * View type for this view, as returned by 5422 * {@link android.widget.Adapter#getItemViewType(int) } 5423 */ 5424 @ViewDebug.ExportedProperty(category = "list", mapping = { 5425 @ViewDebug.IntToString(from = ITEM_VIEW_TYPE_IGNORE, to = "ITEM_VIEW_TYPE_IGNORE"), 5426 @ViewDebug.IntToString(from = ITEM_VIEW_TYPE_HEADER_OR_FOOTER, to = "ITEM_VIEW_TYPE_HEADER_OR_FOOTER") 5427 }) 5428 int viewType; 5429 5430 /** 5431 * When this boolean is set, the view has been added to the AbsListView 5432 * at least once. It is used to know whether headers/footers have already 5433 * been added to the list view and whether they should be treated as 5434 * recycled views or not. 5435 */ 5436 @ViewDebug.ExportedProperty(category = "list") 5437 boolean recycledHeaderFooter; 5438 5439 /** 5440 * When an AbsListView is measured with an AT_MOST measure spec, it needs 5441 * to obtain children views to measure itself. When doing so, the children 5442 * are not attached to the window, but put in the recycler which assumes 5443 * they've been attached before. Setting this flag will force the reused 5444 * view to be attached to the window rather than just attached to the 5445 * parent. 5446 */ 5447 @ViewDebug.ExportedProperty(category = "list") 5448 boolean forceAdd; 5449 5450 /** 5451 * The position the view was removed from when pulled out of the 5452 * scrap heap. 5453 * @hide 5454 */ 5455 int scrappedFromPosition; 5456 5457 public LayoutParams(Context c, AttributeSet attrs) { 5458 super(c, attrs); 5459 } 5460 5461 public LayoutParams(int w, int h) { 5462 super(w, h); 5463 } 5464 5465 public LayoutParams(int w, int h, int viewType) { 5466 super(w, h); 5467 this.viewType = viewType; 5468 } 5469 5470 public LayoutParams(ViewGroup.LayoutParams source) { 5471 super(source); 5472 } 5473 } 5474 5475 /** 5476 * A RecyclerListener is used to receive a notification whenever a View is placed 5477 * inside the RecycleBin's scrap heap. This listener is used to free resources 5478 * associated to Views placed in the RecycleBin. 5479 * 5480 * @see android.widget.AbsListView.RecycleBin 5481 * @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener) 5482 */ 5483 public static interface RecyclerListener { 5484 /** 5485 * Indicates that the specified View was moved into the recycler's scrap heap. 5486 * The view is not displayed on screen any more and any expensive resource 5487 * associated with the view should be discarded. 5488 * 5489 * @param view 5490 */ 5491 void onMovedToScrapHeap(View view); 5492 } 5493 5494 /** 5495 * The RecycleBin facilitates reuse of views across layouts. The RecycleBin has two levels of 5496 * storage: ActiveViews and ScrapViews. ActiveViews are those views which were onscreen at the 5497 * start of a layout. By construction, they are displaying current information. At the end of 5498 * layout, all views in ActiveViews are demoted to ScrapViews. ScrapViews are old views that 5499 * could potentially be used by the adapter to avoid allocating views unnecessarily. 5500 * 5501 * @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener) 5502 * @see android.widget.AbsListView.RecyclerListener 5503 */ 5504 class RecycleBin { 5505 private RecyclerListener mRecyclerListener; 5506 5507 /** 5508 * The position of the first view stored in mActiveViews. 5509 */ 5510 private int mFirstActivePosition; 5511 5512 /** 5513 * Views that were on screen at the start of layout. This array is populated at the start of 5514 * layout, and at the end of layout all view in mActiveViews are moved to mScrapViews. 5515 * Views in mActiveViews represent a contiguous range of Views, with position of the first 5516 * view store in mFirstActivePosition. 5517 */ 5518 private View[] mActiveViews = new View[0]; 5519 5520 /** 5521 * Unsorted views that can be used by the adapter as a convert view. 5522 */ 5523 private ArrayList<View>[] mScrapViews; 5524 5525 private int mViewTypeCount; 5526 5527 private ArrayList<View> mCurrentScrap; 5528 5529 public void setViewTypeCount(int viewTypeCount) { 5530 if (viewTypeCount < 1) { 5531 throw new IllegalArgumentException("Can't have a viewTypeCount < 1"); 5532 } 5533 //noinspection unchecked 5534 ArrayList<View>[] scrapViews = new ArrayList[viewTypeCount]; 5535 for (int i = 0; i < viewTypeCount; i++) { 5536 scrapViews[i] = new ArrayList<View>(); 5537 } 5538 mViewTypeCount = viewTypeCount; 5539 mCurrentScrap = scrapViews[0]; 5540 mScrapViews = scrapViews; 5541 } 5542 5543 public void markChildrenDirty() { 5544 if (mViewTypeCount == 1) { 5545 final ArrayList<View> scrap = mCurrentScrap; 5546 final int scrapCount = scrap.size(); 5547 for (int i = 0; i < scrapCount; i++) { 5548 scrap.get(i).forceLayout(); 5549 } 5550 } else { 5551 final int typeCount = mViewTypeCount; 5552 for (int i = 0; i < typeCount; i++) { 5553 final ArrayList<View> scrap = mScrapViews[i]; 5554 final int scrapCount = scrap.size(); 5555 for (int j = 0; j < scrapCount; j++) { 5556 scrap.get(j).forceLayout(); 5557 } 5558 } 5559 } 5560 } 5561 5562 public boolean shouldRecycleViewType(int viewType) { 5563 return viewType >= 0; 5564 } 5565 5566 /** 5567 * Clears the scrap heap. 5568 */ 5569 void clear() { 5570 if (mViewTypeCount == 1) { 5571 final ArrayList<View> scrap = mCurrentScrap; 5572 final int scrapCount = scrap.size(); 5573 for (int i = 0; i < scrapCount; i++) { 5574 removeDetachedView(scrap.remove(scrapCount - 1 - i), false); 5575 } 5576 } else { 5577 final int typeCount = mViewTypeCount; 5578 for (int i = 0; i < typeCount; i++) { 5579 final ArrayList<View> scrap = mScrapViews[i]; 5580 final int scrapCount = scrap.size(); 5581 for (int j = 0; j < scrapCount; j++) { 5582 removeDetachedView(scrap.remove(scrapCount - 1 - j), false); 5583 } 5584 } 5585 } 5586 } 5587 5588 /** 5589 * Fill ActiveViews with all of the children of the AbsListView. 5590 * 5591 * @param childCount The minimum number of views mActiveViews should hold 5592 * @param firstActivePosition The position of the first view that will be stored in 5593 * mActiveViews 5594 */ 5595 void fillActiveViews(int childCount, int firstActivePosition) { 5596 if (mActiveViews.length < childCount) { 5597 mActiveViews = new View[childCount]; 5598 } 5599 mFirstActivePosition = firstActivePosition; 5600 5601 final View[] activeViews = mActiveViews; 5602 for (int i = 0; i < childCount; i++) { 5603 View child = getChildAt(i); 5604 AbsListView.LayoutParams lp = (AbsListView.LayoutParams) child.getLayoutParams(); 5605 // Don't put header or footer views into the scrap heap 5606 if (lp != null && lp.viewType != ITEM_VIEW_TYPE_HEADER_OR_FOOTER) { 5607 // Note: We do place AdapterView.ITEM_VIEW_TYPE_IGNORE in active views. 5608 // However, we will NOT place them into scrap views. 5609 activeViews[i] = child; 5610 } 5611 } 5612 } 5613 5614 /** 5615 * Get the view corresponding to the specified position. The view will be removed from 5616 * mActiveViews if it is found. 5617 * 5618 * @param position The position to look up in mActiveViews 5619 * @return The view if it is found, null otherwise 5620 */ 5621 View getActiveView(int position) { 5622 int index = position - mFirstActivePosition; 5623 final View[] activeViews = mActiveViews; 5624 if (index >=0 && index < activeViews.length) { 5625 final View match = activeViews[index]; 5626 activeViews[index] = null; 5627 return match; 5628 } 5629 return null; 5630 } 5631 5632 /** 5633 * @return A view from the ScrapViews collection. These are unordered. 5634 */ 5635 View getScrapView(int position) { 5636 if (mViewTypeCount == 1) { 5637 return retrieveFromScrap(mCurrentScrap, position); 5638 } else { 5639 int whichScrap = mAdapter.getItemViewType(position); 5640 if (whichScrap >= 0 && whichScrap < mScrapViews.length) { 5641 return retrieveFromScrap(mScrapViews[whichScrap], position); 5642 } 5643 } 5644 return null; 5645 } 5646 5647 /** 5648 * Put a view into the ScapViews list. These views are unordered. 5649 * 5650 * @param scrap The view to add 5651 */ 5652 void addScrapView(View scrap, int position) { 5653 AbsListView.LayoutParams lp = (AbsListView.LayoutParams) scrap.getLayoutParams(); 5654 if (lp == null) { 5655 return; 5656 } 5657 5658 // Don't put header or footer views or views that should be ignored 5659 // into the scrap heap 5660 int viewType = lp.viewType; 5661 if (!shouldRecycleViewType(viewType)) { 5662 if (viewType != ITEM_VIEW_TYPE_HEADER_OR_FOOTER) { 5663 removeDetachedView(scrap, false); 5664 } 5665 return; 5666 } 5667 5668 lp.scrappedFromPosition = position; 5669 5670 if (mViewTypeCount == 1) { 5671 scrap.dispatchStartTemporaryDetach(); 5672 mCurrentScrap.add(scrap); 5673 } else { 5674 scrap.dispatchStartTemporaryDetach(); 5675 mScrapViews[viewType].add(scrap); 5676 } 5677 5678 if (mRecyclerListener != null) { 5679 mRecyclerListener.onMovedToScrapHeap(scrap); 5680 } 5681 } 5682 5683 /** 5684 * Move all views remaining in mActiveViews to mScrapViews. 5685 */ 5686 void scrapActiveViews() { 5687 final View[] activeViews = mActiveViews; 5688 final boolean hasListener = mRecyclerListener != null; 5689 final boolean multipleScraps = mViewTypeCount > 1; 5690 5691 ArrayList<View> scrapViews = mCurrentScrap; 5692 final int count = activeViews.length; 5693 for (int i = count - 1; i >= 0; i--) { 5694 final View victim = activeViews[i]; 5695 if (victim != null) { 5696 final AbsListView.LayoutParams lp 5697 = (AbsListView.LayoutParams) victim.getLayoutParams(); 5698 int whichScrap = lp.viewType; 5699 5700 activeViews[i] = null; 5701 5702 if (!shouldRecycleViewType(whichScrap)) { 5703 // Do not move views that should be ignored 5704 if (whichScrap != ITEM_VIEW_TYPE_HEADER_OR_FOOTER) { 5705 removeDetachedView(victim, false); 5706 } 5707 continue; 5708 } 5709 5710 if (multipleScraps) { 5711 scrapViews = mScrapViews[whichScrap]; 5712 } 5713 victim.dispatchStartTemporaryDetach(); 5714 lp.scrappedFromPosition = mFirstActivePosition + i; 5715 scrapViews.add(victim); 5716 5717 if (hasListener) { 5718 mRecyclerListener.onMovedToScrapHeap(victim); 5719 } 5720 5721 if (ViewDebug.TRACE_RECYCLER) { 5722 ViewDebug.trace(victim, 5723 ViewDebug.RecyclerTraceType.MOVE_FROM_ACTIVE_TO_SCRAP_HEAP, 5724 mFirstActivePosition + i, -1); 5725 } 5726 } 5727 } 5728 5729 pruneScrapViews(); 5730 } 5731 5732 /** 5733 * Makes sure that the size of mScrapViews does not exceed the size of mActiveViews. 5734 * (This can happen if an adapter does not recycle its views). 5735 */ 5736 private void pruneScrapViews() { 5737 final int maxViews = mActiveViews.length; 5738 final int viewTypeCount = mViewTypeCount; 5739 final ArrayList<View>[] scrapViews = mScrapViews; 5740 for (int i = 0; i < viewTypeCount; ++i) { 5741 final ArrayList<View> scrapPile = scrapViews[i]; 5742 int size = scrapPile.size(); 5743 final int extras = size - maxViews; 5744 size--; 5745 for (int j = 0; j < extras; j++) { 5746 removeDetachedView(scrapPile.remove(size--), false); 5747 } 5748 } 5749 } 5750 5751 /** 5752 * Puts all views in the scrap heap into the supplied list. 5753 */ 5754 void reclaimScrapViews(List<View> views) { 5755 if (mViewTypeCount == 1) { 5756 views.addAll(mCurrentScrap); 5757 } else { 5758 final int viewTypeCount = mViewTypeCount; 5759 final ArrayList<View>[] scrapViews = mScrapViews; 5760 for (int i = 0; i < viewTypeCount; ++i) { 5761 final ArrayList<View> scrapPile = scrapViews[i]; 5762 views.addAll(scrapPile); 5763 } 5764 } 5765 } 5766 5767 /** 5768 * Updates the cache color hint of all known views. 5769 * 5770 * @param color The new cache color hint. 5771 */ 5772 void setCacheColorHint(int color) { 5773 if (mViewTypeCount == 1) { 5774 final ArrayList<View> scrap = mCurrentScrap; 5775 final int scrapCount = scrap.size(); 5776 for (int i = 0; i < scrapCount; i++) { 5777 scrap.get(i).setDrawingCacheBackgroundColor(color); 5778 } 5779 } else { 5780 final int typeCount = mViewTypeCount; 5781 for (int i = 0; i < typeCount; i++) { 5782 final ArrayList<View> scrap = mScrapViews[i]; 5783 final int scrapCount = scrap.size(); 5784 for (int j = 0; j < scrapCount; j++) { 5785 scrap.get(j).setDrawingCacheBackgroundColor(color); 5786 } 5787 } 5788 } 5789 // Just in case this is called during a layout pass 5790 final View[] activeViews = mActiveViews; 5791 final int count = activeViews.length; 5792 for (int i = 0; i < count; ++i) { 5793 final View victim = activeViews[i]; 5794 if (victim != null) { 5795 victim.setDrawingCacheBackgroundColor(color); 5796 } 5797 } 5798 } 5799 } 5800 5801 static View retrieveFromScrap(ArrayList<View> scrapViews, int position) { 5802 int size = scrapViews.size(); 5803 if (size > 0) { 5804 // See if we still have a view for this position. 5805 for (int i=0; i<size; i++) { 5806 View view = scrapViews.get(i); 5807 if (((AbsListView.LayoutParams)view.getLayoutParams()) 5808 .scrappedFromPosition == position) { 5809 scrapViews.remove(i); 5810 return view; 5811 } 5812 } 5813 return scrapViews.remove(size - 1); 5814 } else { 5815 return null; 5816 } 5817 } 5818} 5819