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