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