AbsListView.java revision 947a96956035e1ee22a82d18aec018b9046b641b
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 (canScrollUp()) {
1491                info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
1492                info.setScrollable(true);
1493            }
1494            if (canScrollDown()) {
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            mScrollUp.setVisibility(canScrollUp() ? View.VISIBLE : View.INVISIBLE);
2201        }
2202
2203        if (mScrollDown != null) {
2204            mScrollDown.setVisibility(canScrollDown() ? View.VISIBLE : View.INVISIBLE);
2205        }
2206    }
2207
2208    private boolean canScrollUp() {
2209        boolean canScrollUp;
2210        // 0th element is not visible
2211        canScrollUp = mFirstPosition > 0;
2212
2213        // ... Or top of 0th element is not visible
2214        if (!canScrollUp) {
2215            if (getChildCount() > 0) {
2216                View child = getChildAt(0);
2217                canScrollUp = child.getTop() < mListPadding.top;
2218            }
2219        }
2220
2221        return canScrollUp;
2222    }
2223
2224    private boolean canScrollDown() {
2225        boolean canScrollDown;
2226        int count = getChildCount();
2227
2228        // Last item is not visible
2229        canScrollDown = (mFirstPosition + count) < mItemCount;
2230
2231        // ... Or bottom of the last element is not visible
2232        if (!canScrollDown && count > 0) {
2233            View child = getChildAt(count - 1);
2234            canScrollDown = child.getBottom() > mBottom - mListPadding.bottom;
2235        }
2236
2237        return canScrollDown;
2238    }
2239
2240    @Override
2241    @ViewDebug.ExportedProperty
2242    public View getSelectedView() {
2243        if (mItemCount > 0 && mSelectedPosition >= 0) {
2244            return getChildAt(mSelectedPosition - mFirstPosition);
2245        } else {
2246            return null;
2247        }
2248    }
2249
2250    /**
2251     * List padding is the maximum of the normal view's padding and the padding of the selector.
2252     *
2253     * @see android.view.View#getPaddingTop()
2254     * @see #getSelector()
2255     *
2256     * @return The top list padding.
2257     */
2258    public int getListPaddingTop() {
2259        return mListPadding.top;
2260    }
2261
2262    /**
2263     * List padding is the maximum of the normal view's padding and the padding of the selector.
2264     *
2265     * @see android.view.View#getPaddingBottom()
2266     * @see #getSelector()
2267     *
2268     * @return The bottom list padding.
2269     */
2270    public int getListPaddingBottom() {
2271        return mListPadding.bottom;
2272    }
2273
2274    /**
2275     * List padding is the maximum of the normal view's padding and the padding of the selector.
2276     *
2277     * @see android.view.View#getPaddingLeft()
2278     * @see #getSelector()
2279     *
2280     * @return The left list padding.
2281     */
2282    public int getListPaddingLeft() {
2283        return mListPadding.left;
2284    }
2285
2286    /**
2287     * List padding is the maximum of the normal view's padding and the padding of the selector.
2288     *
2289     * @see android.view.View#getPaddingRight()
2290     * @see #getSelector()
2291     *
2292     * @return The right list padding.
2293     */
2294    public int getListPaddingRight() {
2295        return mListPadding.right;
2296    }
2297
2298    /**
2299     * Get a view and have it show the data associated with the specified
2300     * position. This is called when we have already discovered that the view is
2301     * not available for reuse in the recycle bin. The only choices left are
2302     * converting an old view or making a new one.
2303     *
2304     * @param position The position to display
2305     * @param isScrap Array of at least 1 boolean, the first entry will become true if
2306     *                the returned view was taken from the scrap heap, false if otherwise.
2307     *
2308     * @return A view displaying the data associated with the specified position
2309     */
2310    View obtainView(int position, boolean[] isScrap) {
2311        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "obtainView");
2312
2313        isScrap[0] = false;
2314
2315        // Check whether we have a transient state view. Attempt to re-bind the
2316        // data and discard the view if we fail.
2317        final View transientView = mRecycler.getTransientStateView(position);
2318        if (transientView != null) {
2319            final LayoutParams params = (LayoutParams) transientView.getLayoutParams();
2320
2321            // If the view type hasn't changed, attempt to re-bind the data.
2322            if (params.viewType == mAdapter.getItemViewType(position)) {
2323                final View updatedView = mAdapter.getView(position, transientView, this);
2324
2325                // If we failed to re-bind the data, scrap the obtained view.
2326                if (updatedView != transientView) {
2327                    setItemViewLayoutParams(updatedView, position);
2328                    mRecycler.addScrapView(updatedView, position);
2329                }
2330            }
2331
2332            // Scrap view implies temporary detachment.
2333            isScrap[0] = true;
2334            return transientView;
2335        }
2336
2337        final View scrapView = mRecycler.getScrapView(position);
2338        final View child = mAdapter.getView(position, scrapView, this);
2339        if (scrapView != null) {
2340            if (child != scrapView) {
2341                // Failed to re-bind the data, return scrap to the heap.
2342                mRecycler.addScrapView(scrapView, position);
2343            } else {
2344                isScrap[0] = true;
2345
2346                child.dispatchFinishTemporaryDetach();
2347            }
2348        }
2349
2350        if (mCacheColorHint != 0) {
2351            child.setDrawingCacheBackgroundColor(mCacheColorHint);
2352        }
2353
2354        if (child.getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
2355            child.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
2356        }
2357
2358        setItemViewLayoutParams(child, position);
2359
2360        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2361            if (mAccessibilityDelegate == null) {
2362                mAccessibilityDelegate = new ListItemAccessibilityDelegate();
2363            }
2364            if (child.getAccessibilityDelegate() == null) {
2365                child.setAccessibilityDelegate(mAccessibilityDelegate);
2366            }
2367        }
2368
2369        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2370
2371        return child;
2372    }
2373
2374    private void setItemViewLayoutParams(View child, int position) {
2375        final ViewGroup.LayoutParams vlp = child.getLayoutParams();
2376        LayoutParams lp;
2377        if (vlp == null) {
2378            lp = (LayoutParams) generateDefaultLayoutParams();
2379        } else if (!checkLayoutParams(vlp)) {
2380            lp = (LayoutParams) generateLayoutParams(vlp);
2381        } else {
2382            lp = (LayoutParams) vlp;
2383        }
2384
2385        if (mAdapterHasStableIds) {
2386            lp.itemId = mAdapter.getItemId(position);
2387        }
2388        lp.viewType = mAdapter.getItemViewType(position);
2389        child.setLayoutParams(lp);
2390    }
2391
2392    class ListItemAccessibilityDelegate extends AccessibilityDelegate {
2393        @Override
2394        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
2395            // If the data changed the children are invalid since the data model changed.
2396            // Hence, we pretend they do not exist. After a layout the children will sync
2397            // with the model at which point we notify that the accessibility state changed,
2398            // so a service will be able to re-fetch the views.
2399            if (mDataChanged) {
2400                return null;
2401            }
2402            return super.createAccessibilityNodeInfo(host);
2403        }
2404
2405        @Override
2406        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
2407            super.onInitializeAccessibilityNodeInfo(host, info);
2408
2409            final int position = getPositionForView(host);
2410            onInitializeAccessibilityNodeInfoForItem(host, position, info);
2411        }
2412
2413        @Override
2414        public boolean performAccessibilityAction(View host, int action, Bundle arguments) {
2415            if (super.performAccessibilityAction(host, action, arguments)) {
2416                return true;
2417            }
2418
2419            final int position = getPositionForView(host);
2420            final ListAdapter adapter = getAdapter();
2421
2422            if ((position == INVALID_POSITION) || (adapter == null)) {
2423                // Cannot perform actions on invalid items.
2424                return false;
2425            }
2426
2427            if (!isEnabled() || !adapter.isEnabled(position)) {
2428                // Cannot perform actions on disabled items.
2429                return false;
2430            }
2431
2432            final long id = getItemIdAtPosition(position);
2433
2434            switch (action) {
2435                case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
2436                    if (getSelectedItemPosition() == position) {
2437                        setSelection(INVALID_POSITION);
2438                        return true;
2439                    }
2440                } return false;
2441                case AccessibilityNodeInfo.ACTION_SELECT: {
2442                    if (getSelectedItemPosition() != position) {
2443                        setSelection(position);
2444                        return true;
2445                    }
2446                } return false;
2447                case AccessibilityNodeInfo.ACTION_CLICK: {
2448                    if (isClickable()) {
2449                        return performItemClick(host, position, id);
2450                    }
2451                } return false;
2452                case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
2453                    if (isLongClickable()) {
2454                        return performLongPress(host, position, id);
2455                    }
2456                } return false;
2457            }
2458
2459            return false;
2460        }
2461    }
2462
2463    /**
2464     * Initializes an {@link AccessibilityNodeInfo} with information about a
2465     * particular item in the list.
2466     *
2467     * @param view View representing the list item.
2468     * @param position Position of the list item within the adapter.
2469     * @param info Node info to populate.
2470     */
2471    public void onInitializeAccessibilityNodeInfoForItem(
2472            View view, int position, AccessibilityNodeInfo info) {
2473        final ListAdapter adapter = getAdapter();
2474        if (position == INVALID_POSITION || adapter == null) {
2475            // The item doesn't exist, so there's not much we can do here.
2476            return;
2477        }
2478
2479        if (!isEnabled() || !adapter.isEnabled(position)) {
2480            info.setEnabled(false);
2481            return;
2482        }
2483
2484        if (position == getSelectedItemPosition()) {
2485            info.setSelected(true);
2486            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
2487        } else {
2488            info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
2489        }
2490
2491        if (isClickable()) {
2492            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
2493            info.setClickable(true);
2494        }
2495
2496        if (isLongClickable()) {
2497            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
2498            info.setLongClickable(true);
2499        }
2500    }
2501
2502    /**
2503     * Positions the selector in a way that mimics touch.
2504     */
2505    void positionSelectorLikeTouch(int position, View sel, float x, float y) {
2506        positionSelectorLikeFocus(position, sel);
2507
2508        if (mSelector != null && position != INVALID_POSITION) {
2509            mSelector.setHotspot(x, y);
2510        }
2511    }
2512
2513    /**
2514     * Positions the selector in a way that mimics keyboard focus.
2515     */
2516    void positionSelectorLikeFocus(int position, View sel) {
2517        // If we're changing position, update the visibility since the selector
2518        // is technically being detached from the previous selection.
2519        final Drawable selector = mSelector;
2520        final boolean manageState = selector != null && mSelectorPosition != position
2521                && position != INVALID_POSITION;
2522        if (manageState) {
2523            selector.setVisible(false, false);
2524        }
2525
2526        positionSelector(position, sel);
2527
2528        if (manageState) {
2529            final Rect bounds = mSelectorRect;
2530            final float x = bounds.exactCenterX();
2531            final float y = bounds.exactCenterY();
2532            selector.setVisible(getVisibility() == VISIBLE, false);
2533            selector.setHotspot(x, y);
2534        }
2535    }
2536
2537    void positionSelector(int position, View sel) {
2538        if (position != INVALID_POSITION) {
2539            mSelectorPosition = position;
2540        }
2541
2542        final Rect selectorRect = mSelectorRect;
2543        selectorRect.set(sel.getLeft(), sel.getTop(), sel.getRight(), sel.getBottom());
2544        if (sel instanceof SelectionBoundsAdjuster) {
2545            ((SelectionBoundsAdjuster)sel).adjustListItemSelectionBounds(selectorRect);
2546        }
2547
2548        // Adjust for selection padding.
2549        selectorRect.left -= mSelectionLeftPadding;
2550        selectorRect.top -= mSelectionTopPadding;
2551        selectorRect.right += mSelectionRightPadding;
2552        selectorRect.bottom += mSelectionBottomPadding;
2553
2554        // Update the selector drawable.
2555        final Drawable selector = mSelector;
2556        if (selector != null) {
2557            selector.setBounds(selectorRect);
2558        }
2559
2560        final boolean isChildViewEnabled = mIsChildViewEnabled;
2561        if (sel.isEnabled() != isChildViewEnabled) {
2562            mIsChildViewEnabled = !isChildViewEnabled;
2563            if (getSelectedItemPosition() != INVALID_POSITION) {
2564                refreshDrawableState();
2565            }
2566        }
2567    }
2568
2569    @Override
2570    protected void dispatchDraw(Canvas canvas) {
2571        int saveCount = 0;
2572        final boolean clipToPadding = (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
2573        if (clipToPadding) {
2574            saveCount = canvas.save();
2575            final int scrollX = mScrollX;
2576            final int scrollY = mScrollY;
2577            canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop,
2578                    scrollX + mRight - mLeft - mPaddingRight,
2579                    scrollY + mBottom - mTop - mPaddingBottom);
2580            mGroupFlags &= ~CLIP_TO_PADDING_MASK;
2581        }
2582
2583        final boolean drawSelectorOnTop = mDrawSelectorOnTop;
2584        if (!drawSelectorOnTop) {
2585            drawSelector(canvas);
2586        }
2587
2588        super.dispatchDraw(canvas);
2589
2590        if (drawSelectorOnTop) {
2591            drawSelector(canvas);
2592        }
2593
2594        if (clipToPadding) {
2595            canvas.restoreToCount(saveCount);
2596            mGroupFlags |= CLIP_TO_PADDING_MASK;
2597        }
2598    }
2599
2600    @Override
2601    protected boolean isPaddingOffsetRequired() {
2602        return (mGroupFlags & CLIP_TO_PADDING_MASK) != CLIP_TO_PADDING_MASK;
2603    }
2604
2605    @Override
2606    protected int getLeftPaddingOffset() {
2607        return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : -mPaddingLeft;
2608    }
2609
2610    @Override
2611    protected int getTopPaddingOffset() {
2612        return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : -mPaddingTop;
2613    }
2614
2615    @Override
2616    protected int getRightPaddingOffset() {
2617        return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : mPaddingRight;
2618    }
2619
2620    @Override
2621    protected int getBottomPaddingOffset() {
2622        return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : mPaddingBottom;
2623    }
2624
2625    @Override
2626    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
2627        if (getChildCount() > 0) {
2628            mDataChanged = true;
2629            rememberSyncState();
2630        }
2631
2632        if (mFastScroll != null) {
2633            mFastScroll.onSizeChanged(w, h, oldw, oldh);
2634        }
2635    }
2636
2637    /**
2638     * @return True if the current touch mode requires that we draw the selector in the pressed
2639     *         state.
2640     */
2641    boolean touchModeDrawsInPressedState() {
2642        // FIXME use isPressed for this
2643        switch (mTouchMode) {
2644        case TOUCH_MODE_TAP:
2645        case TOUCH_MODE_DONE_WAITING:
2646            return true;
2647        default:
2648            return false;
2649        }
2650    }
2651
2652    /**
2653     * Indicates whether this view is in a state where the selector should be drawn. This will
2654     * happen if we have focus but are not in touch mode, or we are in the middle of displaying
2655     * the pressed state for an item.
2656     *
2657     * @return True if the selector should be shown
2658     */
2659    boolean shouldShowSelector() {
2660        return (!isInTouchMode()) || (touchModeDrawsInPressedState() && isPressed());
2661    }
2662
2663    private void drawSelector(Canvas canvas) {
2664        if (!mSelectorRect.isEmpty()) {
2665            final Drawable selector = mSelector;
2666            selector.setBounds(mSelectorRect);
2667            selector.draw(canvas);
2668        }
2669    }
2670
2671    /**
2672     * Controls whether the selection highlight drawable should be drawn on top of the item or
2673     * behind it.
2674     *
2675     * @param onTop If true, the selector will be drawn on the item it is highlighting. The default
2676     *        is false.
2677     *
2678     * @attr ref android.R.styleable#AbsListView_drawSelectorOnTop
2679     */
2680    public void setDrawSelectorOnTop(boolean onTop) {
2681        mDrawSelectorOnTop = onTop;
2682    }
2683
2684    /**
2685     * Set a Drawable that should be used to highlight the currently selected item.
2686     *
2687     * @param resID A Drawable resource to use as the selection highlight.
2688     *
2689     * @attr ref android.R.styleable#AbsListView_listSelector
2690     */
2691    public void setSelector(int resID) {
2692        setSelector(getContext().getDrawable(resID));
2693    }
2694
2695    public void setSelector(Drawable sel) {
2696        if (mSelector != null) {
2697            mSelector.setCallback(null);
2698            unscheduleDrawable(mSelector);
2699        }
2700        mSelector = sel;
2701        Rect padding = new Rect();
2702        sel.getPadding(padding);
2703        mSelectionLeftPadding = padding.left;
2704        mSelectionTopPadding = padding.top;
2705        mSelectionRightPadding = padding.right;
2706        mSelectionBottomPadding = padding.bottom;
2707        sel.setCallback(this);
2708        updateSelectorState();
2709    }
2710
2711    /**
2712     * Returns the selector {@link android.graphics.drawable.Drawable} that is used to draw the
2713     * selection in the list.
2714     *
2715     * @return the drawable used to display the selector
2716     */
2717    public Drawable getSelector() {
2718        return mSelector;
2719    }
2720
2721    /**
2722     * Sets the selector state to "pressed" and posts a CheckForKeyLongPress to see if
2723     * this is a long press.
2724     */
2725    void keyPressed() {
2726        if (!isEnabled() || !isClickable()) {
2727            return;
2728        }
2729
2730        Drawable selector = mSelector;
2731        Rect selectorRect = mSelectorRect;
2732        if (selector != null && (isFocused() || touchModeDrawsInPressedState())
2733                && !selectorRect.isEmpty()) {
2734
2735            final View v = getChildAt(mSelectedPosition - mFirstPosition);
2736
2737            if (v != null) {
2738                if (v.hasFocusable()) return;
2739                v.setPressed(true);
2740            }
2741            setPressed(true);
2742
2743            final boolean longClickable = isLongClickable();
2744            Drawable d = selector.getCurrent();
2745            if (d != null && d instanceof TransitionDrawable) {
2746                if (longClickable) {
2747                    ((TransitionDrawable) d).startTransition(
2748                            ViewConfiguration.getLongPressTimeout());
2749                } else {
2750                    ((TransitionDrawable) d).resetTransition();
2751                }
2752            }
2753            if (longClickable && !mDataChanged) {
2754                if (mPendingCheckForKeyLongPress == null) {
2755                    mPendingCheckForKeyLongPress = new CheckForKeyLongPress();
2756                }
2757                mPendingCheckForKeyLongPress.rememberWindowAttachCount();
2758                postDelayed(mPendingCheckForKeyLongPress, ViewConfiguration.getLongPressTimeout());
2759            }
2760        }
2761    }
2762
2763    public void setScrollIndicators(View up, View down) {
2764        mScrollUp = up;
2765        mScrollDown = down;
2766    }
2767
2768    void updateSelectorState() {
2769        if (mSelector != null) {
2770            if (shouldShowSelector()) {
2771                mSelector.setState(getDrawableState());
2772            } else {
2773                mSelector.setState(StateSet.NOTHING);
2774            }
2775        }
2776    }
2777
2778    @Override
2779    protected void drawableStateChanged() {
2780        super.drawableStateChanged();
2781        updateSelectorState();
2782    }
2783
2784    @Override
2785    protected int[] onCreateDrawableState(int extraSpace) {
2786        // If the child view is enabled then do the default behavior.
2787        if (mIsChildViewEnabled) {
2788            // Common case
2789            return super.onCreateDrawableState(extraSpace);
2790        }
2791
2792        // The selector uses this View's drawable state. The selected child view
2793        // is disabled, so we need to remove the enabled state from the drawable
2794        // states.
2795        final int enabledState = ENABLED_STATE_SET[0];
2796
2797        // If we don't have any extra space, it will return one of the static state arrays,
2798        // and clearing the enabled state on those arrays is a bad thing!  If we specify
2799        // we need extra space, it will create+copy into a new array that safely mutable.
2800        int[] state = super.onCreateDrawableState(extraSpace + 1);
2801        int enabledPos = -1;
2802        for (int i = state.length - 1; i >= 0; i--) {
2803            if (state[i] == enabledState) {
2804                enabledPos = i;
2805                break;
2806            }
2807        }
2808
2809        // Remove the enabled state
2810        if (enabledPos >= 0) {
2811            System.arraycopy(state, enabledPos + 1, state, enabledPos,
2812                    state.length - enabledPos - 1);
2813        }
2814
2815        return state;
2816    }
2817
2818    @Override
2819    public boolean verifyDrawable(Drawable dr) {
2820        return mSelector == dr || super.verifyDrawable(dr);
2821    }
2822
2823    @Override
2824    public void jumpDrawablesToCurrentState() {
2825        super.jumpDrawablesToCurrentState();
2826        if (mSelector != null) mSelector.jumpToCurrentState();
2827    }
2828
2829    @Override
2830    protected void onAttachedToWindow() {
2831        super.onAttachedToWindow();
2832
2833        final ViewTreeObserver treeObserver = getViewTreeObserver();
2834        treeObserver.addOnTouchModeChangeListener(this);
2835        if (mTextFilterEnabled && mPopup != null && !mGlobalLayoutListenerAddedFilter) {
2836            treeObserver.addOnGlobalLayoutListener(this);
2837        }
2838
2839        if (mAdapter != null && mDataSetObserver == null) {
2840            mDataSetObserver = new AdapterDataSetObserver();
2841            mAdapter.registerDataSetObserver(mDataSetObserver);
2842
2843            // Data may have changed while we were detached. Refresh.
2844            mDataChanged = true;
2845            mOldItemCount = mItemCount;
2846            mItemCount = mAdapter.getCount();
2847        }
2848    }
2849
2850    @Override
2851    protected void onDetachedFromWindow() {
2852        super.onDetachedFromWindow();
2853
2854        mIsDetaching = true;
2855
2856        // Dismiss the popup in case onSaveInstanceState() was not invoked
2857        dismissPopup();
2858
2859        // Detach any view left in the scrap heap
2860        mRecycler.clear();
2861
2862        final ViewTreeObserver treeObserver = getViewTreeObserver();
2863        treeObserver.removeOnTouchModeChangeListener(this);
2864        if (mTextFilterEnabled && mPopup != null) {
2865            treeObserver.removeOnGlobalLayoutListener(this);
2866            mGlobalLayoutListenerAddedFilter = false;
2867        }
2868
2869        if (mAdapter != null && mDataSetObserver != null) {
2870            mAdapter.unregisterDataSetObserver(mDataSetObserver);
2871            mDataSetObserver = null;
2872        }
2873
2874        if (mScrollStrictSpan != null) {
2875            mScrollStrictSpan.finish();
2876            mScrollStrictSpan = null;
2877        }
2878
2879        if (mFlingStrictSpan != null) {
2880            mFlingStrictSpan.finish();
2881            mFlingStrictSpan = null;
2882        }
2883
2884        if (mFlingRunnable != null) {
2885            removeCallbacks(mFlingRunnable);
2886        }
2887
2888        if (mPositionScroller != null) {
2889            mPositionScroller.stop();
2890        }
2891
2892        if (mClearScrollingCache != null) {
2893            removeCallbacks(mClearScrollingCache);
2894        }
2895
2896        if (mPerformClick != null) {
2897            removeCallbacks(mPerformClick);
2898        }
2899
2900        if (mTouchModeReset != null) {
2901            removeCallbacks(mTouchModeReset);
2902            mTouchModeReset.run();
2903        }
2904
2905        mIsDetaching = false;
2906    }
2907
2908    @Override
2909    public void onWindowFocusChanged(boolean hasWindowFocus) {
2910        super.onWindowFocusChanged(hasWindowFocus);
2911
2912        final int touchMode = isInTouchMode() ? TOUCH_MODE_ON : TOUCH_MODE_OFF;
2913
2914        if (!hasWindowFocus) {
2915            setChildrenDrawingCacheEnabled(false);
2916            if (mFlingRunnable != null) {
2917                removeCallbacks(mFlingRunnable);
2918                // let the fling runnable report it's new state which
2919                // should be idle
2920                mFlingRunnable.endFling();
2921                if (mPositionScroller != null) {
2922                    mPositionScroller.stop();
2923                }
2924                if (mScrollY != 0) {
2925                    mScrollY = 0;
2926                    invalidateParentCaches();
2927                    finishGlows();
2928                    invalidate();
2929                }
2930            }
2931            // Always hide the type filter
2932            dismissPopup();
2933
2934            if (touchMode == TOUCH_MODE_OFF) {
2935                // Remember the last selected element
2936                mResurrectToPosition = mSelectedPosition;
2937            }
2938        } else {
2939            if (mFiltered && !mPopupHidden) {
2940                // Show the type filter only if a filter is in effect
2941                showPopup();
2942            }
2943
2944            // If we changed touch mode since the last time we had focus
2945            if (touchMode != mLastTouchMode && mLastTouchMode != TOUCH_MODE_UNKNOWN) {
2946                // If we come back in trackball mode, we bring the selection back
2947                if (touchMode == TOUCH_MODE_OFF) {
2948                    // This will trigger a layout
2949                    resurrectSelection();
2950
2951                // If we come back in touch mode, then we want to hide the selector
2952                } else {
2953                    hideSelector();
2954                    mLayoutMode = LAYOUT_NORMAL;
2955                    layoutChildren();
2956                }
2957            }
2958        }
2959
2960        mLastTouchMode = touchMode;
2961    }
2962
2963    @Override
2964    public void onRtlPropertiesChanged(int layoutDirection) {
2965        super.onRtlPropertiesChanged(layoutDirection);
2966        if (mFastScroll != null) {
2967           mFastScroll.setScrollbarPosition(getVerticalScrollbarPosition());
2968        }
2969    }
2970
2971    /**
2972     * Creates the ContextMenuInfo returned from {@link #getContextMenuInfo()}. This
2973     * methods knows the view, position and ID of the item that received the
2974     * long press.
2975     *
2976     * @param view The view that received the long press.
2977     * @param position The position of the item that received the long press.
2978     * @param id The ID of the item that received the long press.
2979     * @return The extra information that should be returned by
2980     *         {@link #getContextMenuInfo()}.
2981     */
2982    ContextMenuInfo createContextMenuInfo(View view, int position, long id) {
2983        return new AdapterContextMenuInfo(view, position, id);
2984    }
2985
2986    @Override
2987    public void onCancelPendingInputEvents() {
2988        super.onCancelPendingInputEvents();
2989        if (mPerformClick != null) {
2990            removeCallbacks(mPerformClick);
2991        }
2992        if (mPendingCheckForTap != null) {
2993            removeCallbacks(mPendingCheckForTap);
2994        }
2995        if (mPendingCheckForLongPress != null) {
2996            removeCallbacks(mPendingCheckForLongPress);
2997        }
2998        if (mPendingCheckForKeyLongPress != null) {
2999            removeCallbacks(mPendingCheckForKeyLongPress);
3000        }
3001    }
3002
3003    /**
3004     * A base class for Runnables that will check that their view is still attached to
3005     * the original window as when the Runnable was created.
3006     *
3007     */
3008    private class WindowRunnnable {
3009        private int mOriginalAttachCount;
3010
3011        public void rememberWindowAttachCount() {
3012            mOriginalAttachCount = getWindowAttachCount();
3013        }
3014
3015        public boolean sameWindow() {
3016            return getWindowAttachCount() == mOriginalAttachCount;
3017        }
3018    }
3019
3020    private class PerformClick extends WindowRunnnable implements Runnable {
3021        int mClickMotionPosition;
3022
3023        @Override
3024        public void run() {
3025            // The data has changed since we posted this action in the event queue,
3026            // bail out before bad things happen
3027            if (mDataChanged) return;
3028
3029            final ListAdapter adapter = mAdapter;
3030            final int motionPosition = mClickMotionPosition;
3031            if (adapter != null && mItemCount > 0 &&
3032                    motionPosition != INVALID_POSITION &&
3033                    motionPosition < adapter.getCount() && sameWindow()) {
3034                final View view = getChildAt(motionPosition - mFirstPosition);
3035                // If there is no view, something bad happened (the view scrolled off the
3036                // screen, etc.) and we should cancel the click
3037                if (view != null) {
3038                    performItemClick(view, motionPosition, adapter.getItemId(motionPosition));
3039                }
3040            }
3041        }
3042    }
3043
3044    private class CheckForLongPress extends WindowRunnnable implements Runnable {
3045        @Override
3046        public void run() {
3047            final int motionPosition = mMotionPosition;
3048            final View child = getChildAt(motionPosition - mFirstPosition);
3049            if (child != null) {
3050                final int longPressPosition = mMotionPosition;
3051                final long longPressId = mAdapter.getItemId(mMotionPosition);
3052
3053                boolean handled = false;
3054                if (sameWindow() && !mDataChanged) {
3055                    handled = performLongPress(child, longPressPosition, longPressId);
3056                }
3057                if (handled) {
3058                    mTouchMode = TOUCH_MODE_REST;
3059                    setPressed(false);
3060                    child.setPressed(false);
3061                } else {
3062                    mTouchMode = TOUCH_MODE_DONE_WAITING;
3063                }
3064            }
3065        }
3066    }
3067
3068    private class CheckForKeyLongPress extends WindowRunnnable implements Runnable {
3069        @Override
3070        public void run() {
3071            if (isPressed() && mSelectedPosition >= 0) {
3072                int index = mSelectedPosition - mFirstPosition;
3073                View v = getChildAt(index);
3074
3075                if (!mDataChanged) {
3076                    boolean handled = false;
3077                    if (sameWindow()) {
3078                        handled = performLongPress(v, mSelectedPosition, mSelectedRowId);
3079                    }
3080                    if (handled) {
3081                        setPressed(false);
3082                        v.setPressed(false);
3083                    }
3084                } else {
3085                    setPressed(false);
3086                    if (v != null) v.setPressed(false);
3087                }
3088            }
3089        }
3090    }
3091
3092    boolean performLongPress(final View child,
3093            final int longPressPosition, final long longPressId) {
3094        // CHOICE_MODE_MULTIPLE_MODAL takes over long press.
3095        if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
3096            if (mChoiceActionMode == null &&
3097                    (mChoiceActionMode = startActionMode(mMultiChoiceModeCallback)) != null) {
3098                setItemChecked(longPressPosition, true);
3099                performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3100            }
3101            return true;
3102        }
3103
3104        boolean handled = false;
3105        if (mOnItemLongClickListener != null) {
3106            handled = mOnItemLongClickListener.onItemLongClick(AbsListView.this, child,
3107                    longPressPosition, longPressId);
3108        }
3109        if (!handled) {
3110            mContextMenuInfo = createContextMenuInfo(child, longPressPosition, longPressId);
3111            handled = super.showContextMenuForChild(AbsListView.this);
3112        }
3113        if (handled) {
3114            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3115        }
3116        return handled;
3117    }
3118
3119    @Override
3120    protected ContextMenuInfo getContextMenuInfo() {
3121        return mContextMenuInfo;
3122    }
3123
3124    /** @hide */
3125    @Override
3126    public boolean showContextMenu(float x, float y, int metaState) {
3127        final int position = pointToPosition((int)x, (int)y);
3128        if (position != INVALID_POSITION) {
3129            final long id = mAdapter.getItemId(position);
3130            View child = getChildAt(position - mFirstPosition);
3131            if (child != null) {
3132                mContextMenuInfo = createContextMenuInfo(child, position, id);
3133                return super.showContextMenuForChild(AbsListView.this);
3134            }
3135        }
3136        return super.showContextMenu(x, y, metaState);
3137    }
3138
3139    @Override
3140    public boolean showContextMenuForChild(View originalView) {
3141        final int longPressPosition = getPositionForView(originalView);
3142        if (longPressPosition >= 0) {
3143            final long longPressId = mAdapter.getItemId(longPressPosition);
3144            boolean handled = false;
3145
3146            if (mOnItemLongClickListener != null) {
3147                handled = mOnItemLongClickListener.onItemLongClick(AbsListView.this, originalView,
3148                        longPressPosition, longPressId);
3149            }
3150            if (!handled) {
3151                mContextMenuInfo = createContextMenuInfo(
3152                        getChildAt(longPressPosition - mFirstPosition),
3153                        longPressPosition, longPressId);
3154                handled = super.showContextMenuForChild(originalView);
3155            }
3156
3157            return handled;
3158        }
3159        return false;
3160    }
3161
3162    @Override
3163    public boolean onKeyDown(int keyCode, KeyEvent event) {
3164        return false;
3165    }
3166
3167    @Override
3168    public boolean onKeyUp(int keyCode, KeyEvent event) {
3169        if (KeyEvent.isConfirmKey(keyCode)) {
3170            if (!isEnabled()) {
3171                return true;
3172            }
3173            if (isClickable() && isPressed() &&
3174                    mSelectedPosition >= 0 && mAdapter != null &&
3175                    mSelectedPosition < mAdapter.getCount()) {
3176
3177                final View view = getChildAt(mSelectedPosition - mFirstPosition);
3178                if (view != null) {
3179                    performItemClick(view, mSelectedPosition, mSelectedRowId);
3180                    view.setPressed(false);
3181                }
3182                setPressed(false);
3183                return true;
3184            }
3185        }
3186        return super.onKeyUp(keyCode, event);
3187    }
3188
3189    @Override
3190    protected void dispatchSetPressed(boolean pressed) {
3191        // Don't dispatch setPressed to our children. We call setPressed on ourselves to
3192        // get the selector in the right state, but we don't want to press each child.
3193    }
3194
3195    /**
3196     * Maps a point to a position in the list.
3197     *
3198     * @param x X in local coordinate
3199     * @param y Y in local coordinate
3200     * @return The position of the item which contains the specified point, or
3201     *         {@link #INVALID_POSITION} if the point does not intersect an item.
3202     */
3203    public int pointToPosition(int x, int y) {
3204        Rect frame = mTouchFrame;
3205        if (frame == null) {
3206            mTouchFrame = new Rect();
3207            frame = mTouchFrame;
3208        }
3209
3210        final int count = getChildCount();
3211        for (int i = count - 1; i >= 0; i--) {
3212            final View child = getChildAt(i);
3213            if (child.getVisibility() == View.VISIBLE) {
3214                child.getHitRect(frame);
3215                if (frame.contains(x, y)) {
3216                    return mFirstPosition + i;
3217                }
3218            }
3219        }
3220        return INVALID_POSITION;
3221    }
3222
3223
3224    /**
3225     * Maps a point to a the rowId of the item which intersects that point.
3226     *
3227     * @param x X in local coordinate
3228     * @param y Y in local coordinate
3229     * @return The rowId of the item which contains the specified point, or {@link #INVALID_ROW_ID}
3230     *         if the point does not intersect an item.
3231     */
3232    public long pointToRowId(int x, int y) {
3233        int position = pointToPosition(x, y);
3234        if (position >= 0) {
3235            return mAdapter.getItemId(position);
3236        }
3237        return INVALID_ROW_ID;
3238    }
3239
3240    private final class CheckForTap implements Runnable {
3241        float x;
3242        float y;
3243
3244        @Override
3245        public void run() {
3246            if (mTouchMode == TOUCH_MODE_DOWN) {
3247                mTouchMode = TOUCH_MODE_TAP;
3248                final View child = getChildAt(mMotionPosition - mFirstPosition);
3249                if (child != null && !child.hasFocusable()) {
3250                    mLayoutMode = LAYOUT_NORMAL;
3251
3252                    if (!mDataChanged) {
3253                        child.setPressed(true);
3254                        setPressed(true);
3255                        layoutChildren();
3256                        positionSelector(mMotionPosition, child);
3257                        refreshDrawableState();
3258
3259                        final int longPressTimeout = ViewConfiguration.getLongPressTimeout();
3260                        final boolean longClickable = isLongClickable();
3261
3262                        if (mSelector != null) {
3263                            final Drawable d = mSelector.getCurrent();
3264                            if (d != null && d instanceof TransitionDrawable) {
3265                                if (longClickable) {
3266                                    ((TransitionDrawable) d).startTransition(longPressTimeout);
3267                                } else {
3268                                    ((TransitionDrawable) d).resetTransition();
3269                                }
3270                            }
3271                            mSelector.setHotspot(x, y);
3272                        }
3273
3274                        if (longClickable) {
3275                            if (mPendingCheckForLongPress == null) {
3276                                mPendingCheckForLongPress = new CheckForLongPress();
3277                            }
3278                            mPendingCheckForLongPress.rememberWindowAttachCount();
3279                            postDelayed(mPendingCheckForLongPress, longPressTimeout);
3280                        } else {
3281                            mTouchMode = TOUCH_MODE_DONE_WAITING;
3282                        }
3283                    } else {
3284                        mTouchMode = TOUCH_MODE_DONE_WAITING;
3285                    }
3286                }
3287            }
3288        }
3289    }
3290
3291    private boolean startScrollIfNeeded(int x, int y, MotionEvent vtev) {
3292        // Check if we have moved far enough that it looks more like a
3293        // scroll than a tap
3294        final int deltaY = y - mMotionY;
3295        final int distance = Math.abs(deltaY);
3296        final boolean overscroll = mScrollY != 0;
3297        if ((overscroll || distance > mTouchSlop) &&
3298                (getNestedScrollAxes() & SCROLL_AXIS_VERTICAL) == 0) {
3299            createScrollingCache();
3300            if (overscroll) {
3301                mTouchMode = TOUCH_MODE_OVERSCROLL;
3302                mMotionCorrection = 0;
3303            } else {
3304                mTouchMode = TOUCH_MODE_SCROLL;
3305                mMotionCorrection = deltaY > 0 ? mTouchSlop : -mTouchSlop;
3306            }
3307            removeCallbacks(mPendingCheckForLongPress);
3308            setPressed(false);
3309            final View motionView = getChildAt(mMotionPosition - mFirstPosition);
3310            if (motionView != null) {
3311                motionView.setPressed(false);
3312            }
3313            reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
3314            // Time to start stealing events! Once we've stolen them, don't let anyone
3315            // steal from us
3316            final ViewParent parent = getParent();
3317            if (parent != null) {
3318                parent.requestDisallowInterceptTouchEvent(true);
3319            }
3320            scrollIfNeeded(x, y, vtev);
3321            return true;
3322        }
3323
3324        return false;
3325    }
3326
3327    private void scrollIfNeeded(int x, int y, MotionEvent vtev) {
3328        int rawDeltaY = y - mMotionY;
3329        int scrollOffsetCorrection = 0;
3330        int scrollConsumedCorrection = 0;
3331        if (mLastY == Integer.MIN_VALUE) {
3332            rawDeltaY -= mMotionCorrection;
3333        }
3334        if (dispatchNestedPreScroll(0, mLastY != Integer.MIN_VALUE ? mLastY - y : -rawDeltaY,
3335                mScrollConsumed, mScrollOffset)) {
3336            rawDeltaY += mScrollConsumed[1];
3337            scrollOffsetCorrection = -mScrollOffset[1];
3338            scrollConsumedCorrection = mScrollConsumed[1];
3339            if (vtev != null) {
3340                vtev.offsetLocation(0, mScrollOffset[1]);
3341            }
3342        }
3343        final int deltaY = rawDeltaY;
3344        int incrementalDeltaY =
3345                mLastY != Integer.MIN_VALUE ? y - mLastY + scrollConsumedCorrection : deltaY;
3346        int lastYCorrection = 0;
3347
3348        if (mTouchMode == TOUCH_MODE_SCROLL) {
3349            if (PROFILE_SCROLLING) {
3350                if (!mScrollProfilingStarted) {
3351                    Debug.startMethodTracing("AbsListViewScroll");
3352                    mScrollProfilingStarted = true;
3353                }
3354            }
3355
3356            if (mScrollStrictSpan == null) {
3357                // If it's non-null, we're already in a scroll.
3358                mScrollStrictSpan = StrictMode.enterCriticalSpan("AbsListView-scroll");
3359            }
3360
3361            if (y != mLastY) {
3362                // We may be here after stopping a fling and continuing to scroll.
3363                // If so, we haven't disallowed intercepting touch events yet.
3364                // Make sure that we do so in case we're in a parent that can intercept.
3365                if ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) == 0 &&
3366                        Math.abs(rawDeltaY) > mTouchSlop) {
3367                    final ViewParent parent = getParent();
3368                    if (parent != null) {
3369                        parent.requestDisallowInterceptTouchEvent(true);
3370                    }
3371                }
3372
3373                final int motionIndex;
3374                if (mMotionPosition >= 0) {
3375                    motionIndex = mMotionPosition - mFirstPosition;
3376                } else {
3377                    // If we don't have a motion position that we can reliably track,
3378                    // pick something in the middle to make a best guess at things below.
3379                    motionIndex = getChildCount() / 2;
3380                }
3381
3382                int motionViewPrevTop = 0;
3383                View motionView = this.getChildAt(motionIndex);
3384                if (motionView != null) {
3385                    motionViewPrevTop = motionView.getTop();
3386                }
3387
3388                // No need to do all this work if we're not going to move anyway
3389                boolean atEdge = false;
3390                if (incrementalDeltaY != 0) {
3391                    atEdge = trackMotionScroll(deltaY, incrementalDeltaY);
3392                }
3393
3394                // Check to see if we have bumped into the scroll limit
3395                motionView = this.getChildAt(motionIndex);
3396                if (motionView != null) {
3397                    // Check if the top of the motion view is where it is
3398                    // supposed to be
3399                    final int motionViewRealTop = motionView.getTop();
3400                    if (atEdge) {
3401                        // Apply overscroll
3402
3403                        int overscroll = -incrementalDeltaY -
3404                                (motionViewRealTop - motionViewPrevTop);
3405                        if (dispatchNestedScroll(0, overscroll - incrementalDeltaY, 0, overscroll,
3406                                mScrollOffset)) {
3407                            lastYCorrection -= mScrollOffset[1];
3408                            if (vtev != null) {
3409                                vtev.offsetLocation(0, mScrollOffset[1]);
3410                            }
3411                        } else {
3412                            final boolean atOverscrollEdge = overScrollBy(0, overscroll,
3413                                    0, mScrollY, 0, 0, 0, mOverscrollDistance, true);
3414
3415                            if (atOverscrollEdge && mVelocityTracker != null) {
3416                                // Don't allow overfling if we're at the edge
3417                                mVelocityTracker.clear();
3418                            }
3419
3420                            final int overscrollMode = getOverScrollMode();
3421                            if (overscrollMode == OVER_SCROLL_ALWAYS ||
3422                                    (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS &&
3423                                            !contentFits())) {
3424                                if (!atOverscrollEdge) {
3425                                    mDirection = 0; // Reset when entering overscroll.
3426                                    mTouchMode = TOUCH_MODE_OVERSCROLL;
3427                                }
3428                                if (incrementalDeltaY > 0) {
3429                                    mEdgeGlowTop.onPull((float) -overscroll / getHeight(),
3430                                            (float) x / getWidth());
3431                                    if (!mEdgeGlowBottom.isFinished()) {
3432                                        mEdgeGlowBottom.onRelease();
3433                                    }
3434                                    invalidate(0, 0, getWidth(),
3435                                            mEdgeGlowTop.getMaxHeight() + getPaddingTop());
3436                                } else if (incrementalDeltaY < 0) {
3437                                    mEdgeGlowBottom.onPull((float) overscroll / getHeight(),
3438                                            1.f - (float) x / getWidth());
3439                                    if (!mEdgeGlowTop.isFinished()) {
3440                                        mEdgeGlowTop.onRelease();
3441                                    }
3442                                    invalidate(0, getHeight() - getPaddingBottom() -
3443                                            mEdgeGlowBottom.getMaxHeight(), getWidth(),
3444                                            getHeight());
3445                                }
3446                            }
3447                        }
3448                    }
3449                    mMotionY = y + lastYCorrection + scrollOffsetCorrection;
3450                }
3451                mLastY = y + lastYCorrection + scrollOffsetCorrection;
3452            }
3453        } else if (mTouchMode == TOUCH_MODE_OVERSCROLL) {
3454            if (y != mLastY) {
3455                final int oldScroll = mScrollY;
3456                final int newScroll = oldScroll - incrementalDeltaY;
3457                int newDirection = y > mLastY ? 1 : -1;
3458
3459                if (mDirection == 0) {
3460                    mDirection = newDirection;
3461                }
3462
3463                int overScrollDistance = -incrementalDeltaY;
3464                if ((newScroll < 0 && oldScroll >= 0) || (newScroll > 0 && oldScroll <= 0)) {
3465                    overScrollDistance = -oldScroll;
3466                    incrementalDeltaY += overScrollDistance;
3467                } else {
3468                    incrementalDeltaY = 0;
3469                }
3470
3471                if (overScrollDistance != 0) {
3472                    overScrollBy(0, overScrollDistance, 0, mScrollY, 0, 0,
3473                            0, mOverscrollDistance, true);
3474                    final int overscrollMode = getOverScrollMode();
3475                    if (overscrollMode == OVER_SCROLL_ALWAYS ||
3476                            (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS &&
3477                                    !contentFits())) {
3478                        if (rawDeltaY > 0) {
3479                            mEdgeGlowTop.onPull((float) overScrollDistance / getHeight(),
3480                                    (float) x / getWidth());
3481                            if (!mEdgeGlowBottom.isFinished()) {
3482                                mEdgeGlowBottom.onRelease();
3483                            }
3484                            invalidate(0, 0, getWidth(),
3485                                    mEdgeGlowTop.getMaxHeight() + getPaddingTop());
3486                        } else if (rawDeltaY < 0) {
3487                            mEdgeGlowBottom.onPull((float) overScrollDistance / getHeight(),
3488                                    1.f - (float) x / getWidth());
3489                            if (!mEdgeGlowTop.isFinished()) {
3490                                mEdgeGlowTop.onRelease();
3491                            }
3492                            invalidate(0, getHeight() - getPaddingBottom() -
3493                                    mEdgeGlowBottom.getMaxHeight(), getWidth(),
3494                                    getHeight());
3495                        }
3496                    }
3497                }
3498
3499                if (incrementalDeltaY != 0) {
3500                    // Coming back to 'real' list scrolling
3501                    if (mScrollY != 0) {
3502                        mScrollY = 0;
3503                        invalidateParentIfNeeded();
3504                    }
3505
3506                    trackMotionScroll(incrementalDeltaY, incrementalDeltaY);
3507
3508                    mTouchMode = TOUCH_MODE_SCROLL;
3509
3510                    // We did not scroll the full amount. Treat this essentially like the
3511                    // start of a new touch scroll
3512                    final int motionPosition = findClosestMotionRow(y);
3513
3514                    mMotionCorrection = 0;
3515                    View motionView = getChildAt(motionPosition - mFirstPosition);
3516                    mMotionViewOriginalTop = motionView != null ? motionView.getTop() : 0;
3517                    mMotionY =  y + scrollOffsetCorrection;
3518                    mMotionPosition = motionPosition;
3519                }
3520                mLastY = y + lastYCorrection + scrollOffsetCorrection;
3521                mDirection = newDirection;
3522            }
3523        }
3524    }
3525
3526    @Override
3527    public void onTouchModeChanged(boolean isInTouchMode) {
3528        if (isInTouchMode) {
3529            // Get rid of the selection when we enter touch mode
3530            hideSelector();
3531            // Layout, but only if we already have done so previously.
3532            // (Otherwise may clobber a LAYOUT_SYNC layout that was requested to restore
3533            // state.)
3534            if (getHeight() > 0 && getChildCount() > 0) {
3535                // We do not lose focus initiating a touch (since AbsListView is focusable in
3536                // touch mode). Force an initial layout to get rid of the selection.
3537                layoutChildren();
3538            }
3539            updateSelectorState();
3540        } else {
3541            int touchMode = mTouchMode;
3542            if (touchMode == TOUCH_MODE_OVERSCROLL || touchMode == TOUCH_MODE_OVERFLING) {
3543                if (mFlingRunnable != null) {
3544                    mFlingRunnable.endFling();
3545                }
3546                if (mPositionScroller != null) {
3547                    mPositionScroller.stop();
3548                }
3549
3550                if (mScrollY != 0) {
3551                    mScrollY = 0;
3552                    invalidateParentCaches();
3553                    finishGlows();
3554                    invalidate();
3555                }
3556            }
3557        }
3558    }
3559
3560    @Override
3561    public boolean onTouchEvent(MotionEvent ev) {
3562        if (!isEnabled()) {
3563            // A disabled view that is clickable still consumes the touch
3564            // events, it just doesn't respond to them.
3565            return isClickable() || isLongClickable();
3566        }
3567
3568        if (mPositionScroller != null) {
3569            mPositionScroller.stop();
3570        }
3571
3572        if (mIsDetaching || !isAttachedToWindow()) {
3573            // Something isn't right.
3574            // Since we rely on being attached to get data set change notifications,
3575            // don't risk doing anything where we might try to resync and find things
3576            // in a bogus state.
3577            return false;
3578        }
3579
3580        startNestedScroll(SCROLL_AXIS_VERTICAL);
3581
3582        if (mFastScroll != null) {
3583            boolean intercepted = mFastScroll.onTouchEvent(ev);
3584            if (intercepted) {
3585                return true;
3586            }
3587        }
3588
3589        initVelocityTrackerIfNotExists();
3590        final MotionEvent vtev = MotionEvent.obtain(ev);
3591
3592        final int actionMasked = ev.getActionMasked();
3593        switch (actionMasked) {
3594            case MotionEvent.ACTION_DOWN: {
3595                onTouchDown(ev);
3596                break;
3597            }
3598
3599            case MotionEvent.ACTION_MOVE: {
3600                onTouchMove(ev, vtev);
3601                break;
3602            }
3603
3604            case MotionEvent.ACTION_UP: {
3605                onTouchUp(ev);
3606                break;
3607            }
3608
3609            case MotionEvent.ACTION_CANCEL: {
3610                onTouchCancel();
3611                break;
3612            }
3613
3614            case MotionEvent.ACTION_POINTER_UP: {
3615                onSecondaryPointerUp(ev);
3616                final int x = mMotionX;
3617                final int y = mMotionY;
3618                final int motionPosition = pointToPosition(x, y);
3619                if (motionPosition >= 0) {
3620                    // Remember where the motion event started
3621                    final View child = getChildAt(motionPosition - mFirstPosition);
3622                    mMotionViewOriginalTop = child.getTop();
3623                    mMotionPosition = motionPosition;
3624                }
3625                mLastY = y;
3626                break;
3627            }
3628
3629            case MotionEvent.ACTION_POINTER_DOWN: {
3630                // New pointers take over dragging duties
3631                final int index = ev.getActionIndex();
3632                final int id = ev.getPointerId(index);
3633                final int x = (int) ev.getX(index);
3634                final int y = (int) ev.getY(index);
3635                mMotionCorrection = 0;
3636                mActivePointerId = id;
3637                mMotionX = x;
3638                mMotionY = y;
3639                final int motionPosition = pointToPosition(x, y);
3640                if (motionPosition >= 0) {
3641                    // Remember where the motion event started
3642                    final View child = getChildAt(motionPosition - mFirstPosition);
3643                    mMotionViewOriginalTop = child.getTop();
3644                    mMotionPosition = motionPosition;
3645                }
3646                mLastY = y;
3647                break;
3648            }
3649        }
3650
3651        if (mVelocityTracker != null) {
3652            mVelocityTracker.addMovement(vtev);
3653        }
3654        vtev.recycle();
3655        return true;
3656    }
3657
3658    private void onTouchDown(MotionEvent ev) {
3659        mActivePointerId = ev.getPointerId(0);
3660
3661        if (mTouchMode == TOUCH_MODE_OVERFLING) {
3662            // Stopped the fling. It is a scroll.
3663            mFlingRunnable.endFling();
3664            if (mPositionScroller != null) {
3665                mPositionScroller.stop();
3666            }
3667            mTouchMode = TOUCH_MODE_OVERSCROLL;
3668            mMotionX = (int) ev.getX();
3669            mMotionY = (int) ev.getY();
3670            mLastY = mMotionY;
3671            mMotionCorrection = 0;
3672            mDirection = 0;
3673        } else {
3674            final int x = (int) ev.getX();
3675            final int y = (int) ev.getY();
3676            int motionPosition = pointToPosition(x, y);
3677
3678            if (!mDataChanged) {
3679                if (mTouchMode == TOUCH_MODE_FLING) {
3680                    // Stopped a fling. It is a scroll.
3681                    createScrollingCache();
3682                    mTouchMode = TOUCH_MODE_SCROLL;
3683                    mMotionCorrection = 0;
3684                    motionPosition = findMotionRow(y);
3685                    mFlingRunnable.flywheelTouch();
3686                } else if ((motionPosition >= 0) && getAdapter().isEnabled(motionPosition)) {
3687                    // User clicked on an actual view (and was not stopping a
3688                    // fling). It might be a click or a scroll. Assume it is a
3689                    // click until proven otherwise.
3690                    mTouchMode = TOUCH_MODE_DOWN;
3691
3692                    // FIXME Debounce
3693                    if (mPendingCheckForTap == null) {
3694                        mPendingCheckForTap = new CheckForTap();
3695                    }
3696
3697                    mPendingCheckForTap.x = ev.getX();
3698                    mPendingCheckForTap.y = ev.getY();
3699                    postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
3700                }
3701            }
3702
3703            if (motionPosition >= 0) {
3704                // Remember where the motion event started
3705                final View v = getChildAt(motionPosition - mFirstPosition);
3706                mMotionViewOriginalTop = v.getTop();
3707            }
3708
3709            mMotionX = x;
3710            mMotionY = y;
3711            mMotionPosition = motionPosition;
3712            mLastY = Integer.MIN_VALUE;
3713        }
3714
3715        if (mTouchMode == TOUCH_MODE_DOWN && mMotionPosition != INVALID_POSITION
3716                && performButtonActionOnTouchDown(ev)) {
3717            removeCallbacks(mPendingCheckForTap);
3718        }
3719    }
3720
3721    private void onTouchMove(MotionEvent ev, MotionEvent vtev) {
3722        int pointerIndex = ev.findPointerIndex(mActivePointerId);
3723        if (pointerIndex == -1) {
3724            pointerIndex = 0;
3725            mActivePointerId = ev.getPointerId(pointerIndex);
3726        }
3727
3728        if (mDataChanged) {
3729            // Re-sync everything if data has been changed
3730            // since the scroll operation can query the adapter.
3731            layoutChildren();
3732        }
3733
3734        final int y = (int) ev.getY(pointerIndex);
3735
3736        switch (mTouchMode) {
3737            case TOUCH_MODE_DOWN:
3738            case TOUCH_MODE_TAP:
3739            case TOUCH_MODE_DONE_WAITING:
3740                // Check if we have moved far enough that it looks more like a
3741                // scroll than a tap. If so, we'll enter scrolling mode.
3742                if (startScrollIfNeeded((int) ev.getX(pointerIndex), y, vtev)) {
3743                    break;
3744                }
3745                // Otherwise, check containment within list bounds. If we're
3746                // outside bounds, cancel any active presses.
3747                final float x = ev.getX(pointerIndex);
3748                if (!pointInView(x, y, mTouchSlop)) {
3749                    setPressed(false);
3750                    final View motionView = getChildAt(mMotionPosition - mFirstPosition);
3751                    if (motionView != null) {
3752                        motionView.setPressed(false);
3753                    }
3754                    removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ?
3755                            mPendingCheckForTap : mPendingCheckForLongPress);
3756                    mTouchMode = TOUCH_MODE_DONE_WAITING;
3757                    updateSelectorState();
3758                }
3759                break;
3760            case TOUCH_MODE_SCROLL:
3761            case TOUCH_MODE_OVERSCROLL:
3762                scrollIfNeeded((int) ev.getX(pointerIndex), y, vtev);
3763                break;
3764        }
3765    }
3766
3767    private void onTouchUp(MotionEvent ev) {
3768        switch (mTouchMode) {
3769        case TOUCH_MODE_DOWN:
3770        case TOUCH_MODE_TAP:
3771        case TOUCH_MODE_DONE_WAITING:
3772            final int motionPosition = mMotionPosition;
3773            final View child = getChildAt(motionPosition - mFirstPosition);
3774            if (child != null) {
3775                if (mTouchMode != TOUCH_MODE_DOWN) {
3776                    child.setPressed(false);
3777                }
3778
3779                final float x = ev.getX();
3780                final boolean inList = x > mListPadding.left && x < getWidth() - mListPadding.right;
3781                if (inList && !child.hasFocusable()) {
3782                    if (mPerformClick == null) {
3783                        mPerformClick = new PerformClick();
3784                    }
3785
3786                    final AbsListView.PerformClick performClick = mPerformClick;
3787                    performClick.mClickMotionPosition = motionPosition;
3788                    performClick.rememberWindowAttachCount();
3789
3790                    mResurrectToPosition = motionPosition;
3791
3792                    if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {
3793                        removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ?
3794                                mPendingCheckForTap : mPendingCheckForLongPress);
3795                        mLayoutMode = LAYOUT_NORMAL;
3796                        if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
3797                            mTouchMode = TOUCH_MODE_TAP;
3798                            setSelectedPositionInt(mMotionPosition);
3799                            layoutChildren();
3800                            child.setPressed(true);
3801                            positionSelector(mMotionPosition, child);
3802                            setPressed(true);
3803                            if (mSelector != null) {
3804                                Drawable d = mSelector.getCurrent();
3805                                if (d != null && d instanceof TransitionDrawable) {
3806                                    ((TransitionDrawable) d).resetTransition();
3807                                }
3808                                mSelector.setHotspot(x, ev.getY());
3809                            }
3810                            if (mTouchModeReset != null) {
3811                                removeCallbacks(mTouchModeReset);
3812                            }
3813                            mTouchModeReset = new Runnable() {
3814                                @Override
3815                                public void run() {
3816                                    mTouchModeReset = null;
3817                                    mTouchMode = TOUCH_MODE_REST;
3818                                    child.setPressed(false);
3819                                    setPressed(false);
3820                                    if (!mDataChanged && !mIsDetaching && isAttachedToWindow()) {
3821                                        performClick.run();
3822                                    }
3823                                }
3824                            };
3825                            postDelayed(mTouchModeReset,
3826                                    ViewConfiguration.getPressedStateDuration());
3827                        } else {
3828                            mTouchMode = TOUCH_MODE_REST;
3829                            updateSelectorState();
3830                        }
3831                        return;
3832                    } else if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
3833                        performClick.run();
3834                    }
3835                }
3836            }
3837            mTouchMode = TOUCH_MODE_REST;
3838            updateSelectorState();
3839            break;
3840        case TOUCH_MODE_SCROLL:
3841            final int childCount = getChildCount();
3842            if (childCount > 0) {
3843                final int firstChildTop = getChildAt(0).getTop();
3844                final int lastChildBottom = getChildAt(childCount - 1).getBottom();
3845                final int contentTop = mListPadding.top;
3846                final int contentBottom = getHeight() - mListPadding.bottom;
3847                if (mFirstPosition == 0 && firstChildTop >= contentTop &&
3848                        mFirstPosition + childCount < mItemCount &&
3849                        lastChildBottom <= getHeight() - contentBottom) {
3850                    mTouchMode = TOUCH_MODE_REST;
3851                    reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
3852                } else {
3853                    final VelocityTracker velocityTracker = mVelocityTracker;
3854                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
3855
3856                    final int initialVelocity = (int)
3857                            (velocityTracker.getYVelocity(mActivePointerId) * mVelocityScale);
3858                    // Fling if we have enough velocity and we aren't at a boundary.
3859                    // Since we can potentially overfling more than we can overscroll, don't
3860                    // allow the weird behavior where you can scroll to a boundary then
3861                    // fling further.
3862                    boolean flingVelocity = Math.abs(initialVelocity) > mMinimumVelocity;
3863                    if (flingVelocity &&
3864                            !((mFirstPosition == 0 &&
3865                                    firstChildTop == contentTop - mOverscrollDistance) ||
3866                              (mFirstPosition + childCount == mItemCount &&
3867                                    lastChildBottom == contentBottom + mOverscrollDistance))) {
3868                        if (!dispatchNestedPreFling(0, -initialVelocity)) {
3869                            if (mFlingRunnable == null) {
3870                                mFlingRunnable = new FlingRunnable();
3871                            }
3872                            reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
3873                            mFlingRunnable.start(-initialVelocity);
3874                            dispatchNestedFling(0, -initialVelocity, true);
3875                        } else {
3876                            mTouchMode = TOUCH_MODE_REST;
3877                            reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
3878                        }
3879                    } else {
3880                        mTouchMode = TOUCH_MODE_REST;
3881                        reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
3882                        if (mFlingRunnable != null) {
3883                            mFlingRunnable.endFling();
3884                        }
3885                        if (mPositionScroller != null) {
3886                            mPositionScroller.stop();
3887                        }
3888                        if (flingVelocity && !dispatchNestedPreFling(0, -initialVelocity)) {
3889                            dispatchNestedFling(0, -initialVelocity, false);
3890                        }
3891                    }
3892                }
3893            } else {
3894                mTouchMode = TOUCH_MODE_REST;
3895                reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
3896            }
3897            break;
3898
3899        case TOUCH_MODE_OVERSCROLL:
3900            if (mFlingRunnable == null) {
3901                mFlingRunnable = new FlingRunnable();
3902            }
3903            final VelocityTracker velocityTracker = mVelocityTracker;
3904            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
3905            final int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
3906
3907            reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
3908            if (Math.abs(initialVelocity) > mMinimumVelocity) {
3909                mFlingRunnable.startOverfling(-initialVelocity);
3910            } else {
3911                mFlingRunnable.startSpringback();
3912            }
3913
3914            break;
3915        }
3916
3917        setPressed(false);
3918
3919        if (mEdgeGlowTop != null) {
3920            mEdgeGlowTop.onRelease();
3921            mEdgeGlowBottom.onRelease();
3922        }
3923
3924        // Need to redraw since we probably aren't drawing the selector anymore
3925        invalidate();
3926        removeCallbacks(mPendingCheckForLongPress);
3927        recycleVelocityTracker();
3928
3929        mActivePointerId = INVALID_POINTER;
3930
3931        if (PROFILE_SCROLLING) {
3932            if (mScrollProfilingStarted) {
3933                Debug.stopMethodTracing();
3934                mScrollProfilingStarted = false;
3935            }
3936        }
3937
3938        if (mScrollStrictSpan != null) {
3939            mScrollStrictSpan.finish();
3940            mScrollStrictSpan = null;
3941        }
3942    }
3943
3944    private void onTouchCancel() {
3945        switch (mTouchMode) {
3946        case TOUCH_MODE_OVERSCROLL:
3947            if (mFlingRunnable == null) {
3948                mFlingRunnable = new FlingRunnable();
3949            }
3950            mFlingRunnable.startSpringback();
3951            break;
3952
3953        case TOUCH_MODE_OVERFLING:
3954            // Do nothing - let it play out.
3955            break;
3956
3957        default:
3958            mTouchMode = TOUCH_MODE_REST;
3959            setPressed(false);
3960            final View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
3961            if (motionView != null) {
3962                motionView.setPressed(false);
3963            }
3964            clearScrollingCache();
3965            removeCallbacks(mPendingCheckForLongPress);
3966            recycleVelocityTracker();
3967        }
3968
3969        if (mEdgeGlowTop != null) {
3970            mEdgeGlowTop.onRelease();
3971            mEdgeGlowBottom.onRelease();
3972        }
3973        mActivePointerId = INVALID_POINTER;
3974    }
3975
3976    @Override
3977    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
3978        if (mScrollY != scrollY) {
3979            onScrollChanged(mScrollX, scrollY, mScrollX, mScrollY);
3980            mScrollY = scrollY;
3981            invalidateParentIfNeeded();
3982
3983            awakenScrollBars();
3984        }
3985    }
3986
3987    @Override
3988    public boolean onGenericMotionEvent(MotionEvent event) {
3989        if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3990            switch (event.getAction()) {
3991                case MotionEvent.ACTION_SCROLL: {
3992                    if (mTouchMode == TOUCH_MODE_REST) {
3993                        final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
3994                        if (vscroll != 0) {
3995                            final int delta = (int) (vscroll * getVerticalScrollFactor());
3996                            if (!trackMotionScroll(delta, delta)) {
3997                                return true;
3998                            }
3999                        }
4000                    }
4001                }
4002            }
4003        }
4004        return super.onGenericMotionEvent(event);
4005    }
4006
4007    /**
4008     * Initiate a fling with the given velocity.
4009     *
4010     * <p>Applications can use this method to manually initiate a fling as if the user
4011     * initiated it via touch interaction.</p>
4012     *
4013     * @param velocityY Vertical velocity in pixels per second. Note that this is velocity of
4014     *                  content, not velocity of a touch that initiated the fling.
4015     */
4016    public void fling(int velocityY) {
4017        if (mFlingRunnable == null) {
4018            mFlingRunnable = new FlingRunnable();
4019        }
4020        reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
4021        mFlingRunnable.start(velocityY);
4022    }
4023
4024    @Override
4025    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
4026        return ((nestedScrollAxes & SCROLL_AXIS_VERTICAL) != 0);
4027    }
4028
4029    @Override
4030    public void onNestedScrollAccepted(View child, View target, int axes) {
4031        super.onNestedScrollAccepted(child, target, axes);
4032        startNestedScroll(SCROLL_AXIS_VERTICAL);
4033    }
4034
4035    @Override
4036    public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
4037            int dxUnconsumed, int dyUnconsumed) {
4038        final int motionIndex = getChildCount() / 2;
4039        final View motionView = getChildAt(motionIndex);
4040        final int oldTop = motionView != null ? motionView.getTop() : 0;
4041        if (motionView == null || trackMotionScroll(-dyUnconsumed, -dyUnconsumed)) {
4042            int myUnconsumed = dyUnconsumed;
4043            int myConsumed = 0;
4044            if (motionView != null) {
4045                myConsumed = motionView.getTop() - oldTop;
4046                myUnconsumed -= myConsumed;
4047            }
4048            dispatchNestedScroll(0, myConsumed, 0, myUnconsumed, null);
4049        }
4050    }
4051
4052    @Override
4053    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
4054        final int childCount = getChildCount();
4055        if (!consumed && childCount > 0 && canScrollList((int) velocityY) &&
4056                Math.abs(velocityY) > mMinimumVelocity) {
4057            reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
4058            if (mFlingRunnable == null) {
4059                mFlingRunnable = new FlingRunnable();
4060            }
4061            if (!dispatchNestedPreFling(0, velocityY)) {
4062                mFlingRunnable.start((int) velocityY);
4063            }
4064            return true;
4065        }
4066        return dispatchNestedFling(velocityX, velocityY, consumed);
4067    }
4068
4069    @Override
4070    public void draw(Canvas canvas) {
4071        super.draw(canvas);
4072        if (mEdgeGlowTop != null) {
4073            final int scrollY = mScrollY;
4074            if (!mEdgeGlowTop.isFinished()) {
4075                final int restoreCount = canvas.save();
4076                final int width = getWidth();
4077
4078                int edgeY = Math.min(0, scrollY + mFirstPositionDistanceGuess);
4079                canvas.translate(0, edgeY);
4080                mEdgeGlowTop.setSize(width, getHeight());
4081                if (mEdgeGlowTop.draw(canvas)) {
4082                    invalidate(0, 0, getWidth(),
4083                            mEdgeGlowTop.getMaxHeight() + getPaddingTop());
4084                }
4085                canvas.restoreToCount(restoreCount);
4086            }
4087            if (!mEdgeGlowBottom.isFinished()) {
4088                final int restoreCount = canvas.save();
4089                final int width = getWidth();
4090                final int height = getHeight();
4091
4092                int edgeX = -width;
4093                int edgeY = Math.max(height, scrollY + mLastPositionDistanceGuess);
4094                canvas.translate(edgeX, edgeY);
4095                canvas.rotate(180, width, 0);
4096                mEdgeGlowBottom.setSize(width, height);
4097                if (mEdgeGlowBottom.draw(canvas)) {
4098                    invalidate(0, getHeight() - getPaddingBottom() -
4099                            mEdgeGlowBottom.getMaxHeight(), getWidth(),
4100                            getHeight());
4101                }
4102                canvas.restoreToCount(restoreCount);
4103            }
4104        }
4105    }
4106
4107    /**
4108     * @hide
4109     */
4110    public void setOverScrollEffectPadding(int leftPadding, int rightPadding) {
4111        mGlowPaddingLeft = leftPadding;
4112        mGlowPaddingRight = rightPadding;
4113    }
4114
4115    private void initOrResetVelocityTracker() {
4116        if (mVelocityTracker == null) {
4117            mVelocityTracker = VelocityTracker.obtain();
4118        } else {
4119            mVelocityTracker.clear();
4120        }
4121    }
4122
4123    private void initVelocityTrackerIfNotExists() {
4124        if (mVelocityTracker == null) {
4125            mVelocityTracker = VelocityTracker.obtain();
4126        }
4127    }
4128
4129    private void recycleVelocityTracker() {
4130        if (mVelocityTracker != null) {
4131            mVelocityTracker.recycle();
4132            mVelocityTracker = null;
4133        }
4134    }
4135
4136    @Override
4137    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
4138        if (disallowIntercept) {
4139            recycleVelocityTracker();
4140        }
4141        super.requestDisallowInterceptTouchEvent(disallowIntercept);
4142    }
4143
4144    @Override
4145    public boolean onInterceptHoverEvent(MotionEvent event) {
4146        if (mFastScroll != null && mFastScroll.onInterceptHoverEvent(event)) {
4147            return true;
4148        }
4149
4150        return super.onInterceptHoverEvent(event);
4151    }
4152
4153    @Override
4154    public boolean onInterceptTouchEvent(MotionEvent ev) {
4155        int action = ev.getAction();
4156        View v;
4157
4158        if (mPositionScroller != null) {
4159            mPositionScroller.stop();
4160        }
4161
4162        if (mIsDetaching || !isAttachedToWindow()) {
4163            // Something isn't right.
4164            // Since we rely on being attached to get data set change notifications,
4165            // don't risk doing anything where we might try to resync and find things
4166            // in a bogus state.
4167            return false;
4168        }
4169
4170        if (mFastScroll != null && mFastScroll.onInterceptTouchEvent(ev)) {
4171            return true;
4172        }
4173
4174        switch (action & MotionEvent.ACTION_MASK) {
4175        case MotionEvent.ACTION_DOWN: {
4176            int touchMode = mTouchMode;
4177            if (touchMode == TOUCH_MODE_OVERFLING || touchMode == TOUCH_MODE_OVERSCROLL) {
4178                mMotionCorrection = 0;
4179                return true;
4180            }
4181
4182            final int x = (int) ev.getX();
4183            final int y = (int) ev.getY();
4184            mActivePointerId = ev.getPointerId(0);
4185
4186            int motionPosition = findMotionRow(y);
4187            if (touchMode != TOUCH_MODE_FLING && motionPosition >= 0) {
4188                // User clicked on an actual view (and was not stopping a fling).
4189                // Remember where the motion event started
4190                v = getChildAt(motionPosition - mFirstPosition);
4191                mMotionViewOriginalTop = v.getTop();
4192                mMotionX = x;
4193                mMotionY = y;
4194                mMotionPosition = motionPosition;
4195                mTouchMode = TOUCH_MODE_DOWN;
4196                clearScrollingCache();
4197            }
4198            mLastY = Integer.MIN_VALUE;
4199            initOrResetVelocityTracker();
4200            mVelocityTracker.addMovement(ev);
4201            startNestedScroll(SCROLL_AXIS_VERTICAL);
4202            if (touchMode == TOUCH_MODE_FLING) {
4203                return true;
4204            }
4205            break;
4206        }
4207
4208        case MotionEvent.ACTION_MOVE: {
4209            switch (mTouchMode) {
4210            case TOUCH_MODE_DOWN:
4211                int pointerIndex = ev.findPointerIndex(mActivePointerId);
4212                if (pointerIndex == -1) {
4213                    pointerIndex = 0;
4214                    mActivePointerId = ev.getPointerId(pointerIndex);
4215                }
4216                final int y = (int) ev.getY(pointerIndex);
4217                initVelocityTrackerIfNotExists();
4218                mVelocityTracker.addMovement(ev);
4219                if (startScrollIfNeeded((int) ev.getX(pointerIndex), y, null)) {
4220                    return true;
4221                }
4222                break;
4223            }
4224            break;
4225        }
4226
4227        case MotionEvent.ACTION_CANCEL:
4228        case MotionEvent.ACTION_UP: {
4229            mTouchMode = TOUCH_MODE_REST;
4230            mActivePointerId = INVALID_POINTER;
4231            recycleVelocityTracker();
4232            reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
4233            stopNestedScroll();
4234            break;
4235        }
4236
4237        case MotionEvent.ACTION_POINTER_UP: {
4238            onSecondaryPointerUp(ev);
4239            break;
4240        }
4241        }
4242
4243        return false;
4244    }
4245
4246    private void onSecondaryPointerUp(MotionEvent ev) {
4247        final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
4248                MotionEvent.ACTION_POINTER_INDEX_SHIFT;
4249        final int pointerId = ev.getPointerId(pointerIndex);
4250        if (pointerId == mActivePointerId) {
4251            // This was our active pointer going up. Choose a new
4252            // active pointer and adjust accordingly.
4253            // TODO: Make this decision more intelligent.
4254            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
4255            mMotionX = (int) ev.getX(newPointerIndex);
4256            mMotionY = (int) ev.getY(newPointerIndex);
4257            mMotionCorrection = 0;
4258            mActivePointerId = ev.getPointerId(newPointerIndex);
4259        }
4260    }
4261
4262    /**
4263     * {@inheritDoc}
4264     */
4265    @Override
4266    public void addTouchables(ArrayList<View> views) {
4267        final int count = getChildCount();
4268        final int firstPosition = mFirstPosition;
4269        final ListAdapter adapter = mAdapter;
4270
4271        if (adapter == null) {
4272            return;
4273        }
4274
4275        for (int i = 0; i < count; i++) {
4276            final View child = getChildAt(i);
4277            if (adapter.isEnabled(firstPosition + i)) {
4278                views.add(child);
4279            }
4280            child.addTouchables(views);
4281        }
4282    }
4283
4284    /**
4285     * Fires an "on scroll state changed" event to the registered
4286     * {@link android.widget.AbsListView.OnScrollListener}, if any. The state change
4287     * is fired only if the specified state is different from the previously known state.
4288     *
4289     * @param newState The new scroll state.
4290     */
4291    void reportScrollStateChange(int newState) {
4292        if (newState != mLastScrollState) {
4293            if (mOnScrollListener != null) {
4294                mLastScrollState = newState;
4295                mOnScrollListener.onScrollStateChanged(this, newState);
4296            }
4297        }
4298    }
4299
4300    /**
4301     * Responsible for fling behavior. Use {@link #start(int)} to
4302     * initiate a fling. Each frame of the fling is handled in {@link #run()}.
4303     * A FlingRunnable will keep re-posting itself until the fling is done.
4304     *
4305     */
4306    private class FlingRunnable implements Runnable {
4307        /**
4308         * Tracks the decay of a fling scroll
4309         */
4310        private final OverScroller mScroller;
4311
4312        /**
4313         * Y value reported by mScroller on the previous fling
4314         */
4315        private int mLastFlingY;
4316
4317        private final Runnable mCheckFlywheel = new Runnable() {
4318            @Override
4319            public void run() {
4320                final int activeId = mActivePointerId;
4321                final VelocityTracker vt = mVelocityTracker;
4322                final OverScroller scroller = mScroller;
4323                if (vt == null || activeId == INVALID_POINTER) {
4324                    return;
4325                }
4326
4327                vt.computeCurrentVelocity(1000, mMaximumVelocity);
4328                final float yvel = -vt.getYVelocity(activeId);
4329
4330                if (Math.abs(yvel) >= mMinimumVelocity
4331                        && scroller.isScrollingInDirection(0, yvel)) {
4332                    // Keep the fling alive a little longer
4333                    postDelayed(this, FLYWHEEL_TIMEOUT);
4334                } else {
4335                    endFling();
4336                    mTouchMode = TOUCH_MODE_SCROLL;
4337                    reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
4338                }
4339            }
4340        };
4341
4342        private static final int FLYWHEEL_TIMEOUT = 40; // milliseconds
4343
4344        FlingRunnable() {
4345            mScroller = new OverScroller(getContext());
4346        }
4347
4348        void start(int initialVelocity) {
4349            int initialY = initialVelocity < 0 ? Integer.MAX_VALUE : 0;
4350            mLastFlingY = initialY;
4351            mScroller.setInterpolator(null);
4352            mScroller.fling(0, initialY, 0, initialVelocity,
4353                    0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);
4354            mTouchMode = TOUCH_MODE_FLING;
4355            postOnAnimation(this);
4356
4357            if (PROFILE_FLINGING) {
4358                if (!mFlingProfilingStarted) {
4359                    Debug.startMethodTracing("AbsListViewFling");
4360                    mFlingProfilingStarted = true;
4361                }
4362            }
4363
4364            if (mFlingStrictSpan == null) {
4365                mFlingStrictSpan = StrictMode.enterCriticalSpan("AbsListView-fling");
4366            }
4367        }
4368
4369        void startSpringback() {
4370            if (mScroller.springBack(0, mScrollY, 0, 0, 0, 0)) {
4371                mTouchMode = TOUCH_MODE_OVERFLING;
4372                invalidate();
4373                postOnAnimation(this);
4374            } else {
4375                mTouchMode = TOUCH_MODE_REST;
4376                reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
4377            }
4378        }
4379
4380        void startOverfling(int initialVelocity) {
4381            mScroller.setInterpolator(null);
4382            mScroller.fling(0, mScrollY, 0, initialVelocity, 0, 0,
4383                    Integer.MIN_VALUE, Integer.MAX_VALUE, 0, getHeight());
4384            mTouchMode = TOUCH_MODE_OVERFLING;
4385            invalidate();
4386            postOnAnimation(this);
4387        }
4388
4389        void edgeReached(int delta) {
4390            mScroller.notifyVerticalEdgeReached(mScrollY, 0, mOverflingDistance);
4391            final int overscrollMode = getOverScrollMode();
4392            if (overscrollMode == OVER_SCROLL_ALWAYS ||
4393                    (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && !contentFits())) {
4394                mTouchMode = TOUCH_MODE_OVERFLING;
4395                final int vel = (int) mScroller.getCurrVelocity();
4396                if (delta > 0) {
4397                    mEdgeGlowTop.onAbsorb(vel);
4398                } else {
4399                    mEdgeGlowBottom.onAbsorb(vel);
4400                }
4401            } else {
4402                mTouchMode = TOUCH_MODE_REST;
4403                if (mPositionScroller != null) {
4404                    mPositionScroller.stop();
4405                }
4406            }
4407            invalidate();
4408            postOnAnimation(this);
4409        }
4410
4411        void startScroll(int distance, int duration, boolean linear) {
4412            int initialY = distance < 0 ? Integer.MAX_VALUE : 0;
4413            mLastFlingY = initialY;
4414            mScroller.setInterpolator(linear ? sLinearInterpolator : null);
4415            mScroller.startScroll(0, initialY, 0, distance, duration);
4416            mTouchMode = TOUCH_MODE_FLING;
4417            postOnAnimation(this);
4418        }
4419
4420        void endFling() {
4421            mTouchMode = TOUCH_MODE_REST;
4422
4423            removeCallbacks(this);
4424            removeCallbacks(mCheckFlywheel);
4425
4426            reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
4427            clearScrollingCache();
4428            mScroller.abortAnimation();
4429
4430            if (mFlingStrictSpan != null) {
4431                mFlingStrictSpan.finish();
4432                mFlingStrictSpan = null;
4433            }
4434        }
4435
4436        void flywheelTouch() {
4437            postDelayed(mCheckFlywheel, FLYWHEEL_TIMEOUT);
4438        }
4439
4440        @Override
4441        public void run() {
4442            switch (mTouchMode) {
4443            default:
4444                endFling();
4445                return;
4446
4447            case TOUCH_MODE_SCROLL:
4448                if (mScroller.isFinished()) {
4449                    return;
4450                }
4451                // Fall through
4452            case TOUCH_MODE_FLING: {
4453                if (mDataChanged) {
4454                    layoutChildren();
4455                }
4456
4457                if (mItemCount == 0 || getChildCount() == 0) {
4458                    endFling();
4459                    return;
4460                }
4461
4462                final OverScroller scroller = mScroller;
4463                boolean more = scroller.computeScrollOffset();
4464                final int y = scroller.getCurrY();
4465
4466                // Flip sign to convert finger direction to list items direction
4467                // (e.g. finger moving down means list is moving towards the top)
4468                int delta = mLastFlingY - y;
4469
4470                // Pretend that each frame of a fling scroll is a touch scroll
4471                if (delta > 0) {
4472                    // List is moving towards the top. Use first view as mMotionPosition
4473                    mMotionPosition = mFirstPosition;
4474                    final View firstView = getChildAt(0);
4475                    mMotionViewOriginalTop = firstView.getTop();
4476
4477                    // Don't fling more than 1 screen
4478                    delta = Math.min(getHeight() - mPaddingBottom - mPaddingTop - 1, delta);
4479                } else {
4480                    // List is moving towards the bottom. Use last view as mMotionPosition
4481                    int offsetToLast = getChildCount() - 1;
4482                    mMotionPosition = mFirstPosition + offsetToLast;
4483
4484                    final View lastView = getChildAt(offsetToLast);
4485                    mMotionViewOriginalTop = lastView.getTop();
4486
4487                    // Don't fling more than 1 screen
4488                    delta = Math.max(-(getHeight() - mPaddingBottom - mPaddingTop - 1), delta);
4489                }
4490
4491                // Check to see if we have bumped into the scroll limit
4492                View motionView = getChildAt(mMotionPosition - mFirstPosition);
4493                int oldTop = 0;
4494                if (motionView != null) {
4495                    oldTop = motionView.getTop();
4496                }
4497
4498                // Don't stop just because delta is zero (it could have been rounded)
4499                final boolean atEdge = trackMotionScroll(delta, delta);
4500                final boolean atEnd = atEdge && (delta != 0);
4501                if (atEnd) {
4502                    if (motionView != null) {
4503                        // Tweak the scroll for how far we overshot
4504                        int overshoot = -(delta - (motionView.getTop() - oldTop));
4505                        overScrollBy(0, overshoot, 0, mScrollY, 0, 0,
4506                                0, mOverflingDistance, false);
4507                    }
4508                    if (more) {
4509                        edgeReached(delta);
4510                    }
4511                    break;
4512                }
4513
4514                if (more && !atEnd) {
4515                    if (atEdge) invalidate();
4516                    mLastFlingY = y;
4517                    postOnAnimation(this);
4518                } else {
4519                    endFling();
4520
4521                    if (PROFILE_FLINGING) {
4522                        if (mFlingProfilingStarted) {
4523                            Debug.stopMethodTracing();
4524                            mFlingProfilingStarted = false;
4525                        }
4526
4527                        if (mFlingStrictSpan != null) {
4528                            mFlingStrictSpan.finish();
4529                            mFlingStrictSpan = null;
4530                        }
4531                    }
4532                }
4533                break;
4534            }
4535
4536            case TOUCH_MODE_OVERFLING: {
4537                final OverScroller scroller = mScroller;
4538                if (scroller.computeScrollOffset()) {
4539                    final int scrollY = mScrollY;
4540                    final int currY = scroller.getCurrY();
4541                    final int deltaY = currY - scrollY;
4542                    if (overScrollBy(0, deltaY, 0, scrollY, 0, 0,
4543                            0, mOverflingDistance, false)) {
4544                        final boolean crossDown = scrollY <= 0 && currY > 0;
4545                        final boolean crossUp = scrollY >= 0 && currY < 0;
4546                        if (crossDown || crossUp) {
4547                            int velocity = (int) scroller.getCurrVelocity();
4548                            if (crossUp) velocity = -velocity;
4549
4550                            // Don't flywheel from this; we're just continuing things.
4551                            scroller.abortAnimation();
4552                            start(velocity);
4553                        } else {
4554                            startSpringback();
4555                        }
4556                    } else {
4557                        invalidate();
4558                        postOnAnimation(this);
4559                    }
4560                } else {
4561                    endFling();
4562                }
4563                break;
4564            }
4565            }
4566        }
4567    }
4568
4569    /**
4570     * The amount of friction applied to flings. The default value
4571     * is {@link ViewConfiguration#getScrollFriction}.
4572     */
4573    public void setFriction(float friction) {
4574        if (mFlingRunnable == null) {
4575            mFlingRunnable = new FlingRunnable();
4576        }
4577        mFlingRunnable.mScroller.setFriction(friction);
4578    }
4579
4580    /**
4581     * Sets a scale factor for the fling velocity. The initial scale
4582     * factor is 1.0.
4583     *
4584     * @param scale The scale factor to multiply the velocity by.
4585     */
4586    public void setVelocityScale(float scale) {
4587        mVelocityScale = scale;
4588    }
4589
4590    /**
4591     * Override this for better control over position scrolling.
4592     */
4593    AbsPositionScroller createPositionScroller() {
4594        return new PositionScroller();
4595    }
4596
4597    /**
4598     * Smoothly scroll to the specified adapter position. The view will
4599     * scroll such that the indicated position is displayed.
4600     * @param position Scroll to this adapter position.
4601     */
4602    public void smoothScrollToPosition(int position) {
4603        if (mPositionScroller == null) {
4604            mPositionScroller = createPositionScroller();
4605        }
4606        mPositionScroller.start(position);
4607    }
4608
4609    /**
4610     * Smoothly scroll to the specified adapter position. The view will scroll
4611     * such that the indicated position is displayed <code>offset</code> pixels below
4612     * the top edge of the view. If this is impossible, (e.g. the offset would scroll
4613     * the first or last item beyond the boundaries of the list) it will get as close
4614     * as possible. The scroll will take <code>duration</code> milliseconds to complete.
4615     *
4616     * @param position Position to scroll to
4617     * @param offset Desired distance in pixels of <code>position</code> from the top
4618     *               of the view when scrolling is finished
4619     * @param duration Number of milliseconds to use for the scroll
4620     */
4621    public void smoothScrollToPositionFromTop(int position, int offset, int duration) {
4622        if (mPositionScroller == null) {
4623            mPositionScroller = createPositionScroller();
4624        }
4625        mPositionScroller.startWithOffset(position, offset, duration);
4626    }
4627
4628    /**
4629     * Smoothly scroll to the specified adapter position. The view will scroll
4630     * such that the indicated position is displayed <code>offset</code> pixels below
4631     * the top edge of the view. If this is impossible, (e.g. the offset would scroll
4632     * the first or last item beyond the boundaries of the list) it will get as close
4633     * as possible.
4634     *
4635     * @param position Position to scroll to
4636     * @param offset Desired distance in pixels of <code>position</code> from the top
4637     *               of the view when scrolling is finished
4638     */
4639    public void smoothScrollToPositionFromTop(int position, int offset) {
4640        if (mPositionScroller == null) {
4641            mPositionScroller = createPositionScroller();
4642        }
4643        mPositionScroller.startWithOffset(position, offset, offset);
4644    }
4645
4646    /**
4647     * Smoothly scroll to the specified adapter position. The view will
4648     * scroll such that the indicated position is displayed, but it will
4649     * stop early if scrolling further would scroll boundPosition out of
4650     * view.
4651     *
4652     * @param position Scroll to this adapter position.
4653     * @param boundPosition Do not scroll if it would move this adapter
4654     *          position out of view.
4655     */
4656    public void smoothScrollToPosition(int position, int boundPosition) {
4657        if (mPositionScroller == null) {
4658            mPositionScroller = createPositionScroller();
4659        }
4660        mPositionScroller.start(position, boundPosition);
4661    }
4662
4663    /**
4664     * Smoothly scroll by distance pixels over duration milliseconds.
4665     * @param distance Distance to scroll in pixels.
4666     * @param duration Duration of the scroll animation in milliseconds.
4667     */
4668    public void smoothScrollBy(int distance, int duration) {
4669        smoothScrollBy(distance, duration, false);
4670    }
4671
4672    void smoothScrollBy(int distance, int duration, boolean linear) {
4673        if (mFlingRunnable == null) {
4674            mFlingRunnable = new FlingRunnable();
4675        }
4676
4677        // No sense starting to scroll if we're not going anywhere
4678        final int firstPos = mFirstPosition;
4679        final int childCount = getChildCount();
4680        final int lastPos = firstPos + childCount;
4681        final int topLimit = getPaddingTop();
4682        final int bottomLimit = getHeight() - getPaddingBottom();
4683
4684        if (distance == 0 || mItemCount == 0 || childCount == 0 ||
4685                (firstPos == 0 && getChildAt(0).getTop() == topLimit && distance < 0) ||
4686                (lastPos == mItemCount &&
4687                        getChildAt(childCount - 1).getBottom() == bottomLimit && distance > 0)) {
4688            mFlingRunnable.endFling();
4689            if (mPositionScroller != null) {
4690                mPositionScroller.stop();
4691            }
4692        } else {
4693            reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
4694            mFlingRunnable.startScroll(distance, duration, linear);
4695        }
4696    }
4697
4698    /**
4699     * Allows RemoteViews to scroll relatively to a position.
4700     */
4701    void smoothScrollByOffset(int position) {
4702        int index = -1;
4703        if (position < 0) {
4704            index = getFirstVisiblePosition();
4705        } else if (position > 0) {
4706            index = getLastVisiblePosition();
4707        }
4708
4709        if (index > -1) {
4710            View child = getChildAt(index - getFirstVisiblePosition());
4711            if (child != null) {
4712                Rect visibleRect = new Rect();
4713                if (child.getGlobalVisibleRect(visibleRect)) {
4714                    // the child is partially visible
4715                    int childRectArea = child.getWidth() * child.getHeight();
4716                    int visibleRectArea = visibleRect.width() * visibleRect.height();
4717                    float visibleArea = (visibleRectArea / (float) childRectArea);
4718                    final float visibleThreshold = 0.75f;
4719                    if ((position < 0) && (visibleArea < visibleThreshold)) {
4720                        // the top index is not perceivably visible so offset
4721                        // to account for showing that top index as well
4722                        ++index;
4723                    } else if ((position > 0) && (visibleArea < visibleThreshold)) {
4724                        // the bottom index is not perceivably visible so offset
4725                        // to account for showing that bottom index as well
4726                        --index;
4727                    }
4728                }
4729                smoothScrollToPosition(Math.max(0, Math.min(getCount(), index + position)));
4730            }
4731        }
4732    }
4733
4734    private void createScrollingCache() {
4735        if (mScrollingCacheEnabled && !mCachingStarted && !isHardwareAccelerated()) {
4736            setChildrenDrawnWithCacheEnabled(true);
4737            setChildrenDrawingCacheEnabled(true);
4738            mCachingStarted = mCachingActive = true;
4739        }
4740    }
4741
4742    private void clearScrollingCache() {
4743        if (!isHardwareAccelerated()) {
4744            if (mClearScrollingCache == null) {
4745                mClearScrollingCache = new Runnable() {
4746                    @Override
4747                    public void run() {
4748                        if (mCachingStarted) {
4749                            mCachingStarted = mCachingActive = false;
4750                            setChildrenDrawnWithCacheEnabled(false);
4751                            if ((mPersistentDrawingCache & PERSISTENT_SCROLLING_CACHE) == 0) {
4752                                setChildrenDrawingCacheEnabled(false);
4753                            }
4754                            if (!isAlwaysDrawnWithCacheEnabled()) {
4755                                invalidate();
4756                            }
4757                        }
4758                    }
4759                };
4760            }
4761            post(mClearScrollingCache);
4762        }
4763    }
4764
4765    /**
4766     * Scrolls the list items within the view by a specified number of pixels.
4767     *
4768     * @param y the amount of pixels to scroll by vertically
4769     * @see #canScrollList(int)
4770     */
4771    public void scrollListBy(int y) {
4772        trackMotionScroll(-y, -y);
4773    }
4774
4775    /**
4776     * Check if the items in the list can be scrolled in a certain direction.
4777     *
4778     * @param direction Negative to check scrolling up, positive to check
4779     *            scrolling down.
4780     * @return true if the list can be scrolled in the specified direction,
4781     *         false otherwise.
4782     * @see #scrollListBy(int)
4783     */
4784    public boolean canScrollList(int direction) {
4785        final int childCount = getChildCount();
4786        if (childCount == 0) {
4787            return false;
4788        }
4789
4790        final int firstPosition = mFirstPosition;
4791        final Rect listPadding = mListPadding;
4792        if (direction > 0) {
4793            final int lastBottom = getChildAt(childCount - 1).getBottom();
4794            final int lastPosition = firstPosition + childCount;
4795            return lastPosition < mItemCount || lastBottom > getHeight() - listPadding.bottom;
4796        } else {
4797            final int firstTop = getChildAt(0).getTop();
4798            return firstPosition > 0 || firstTop < listPadding.top;
4799        }
4800    }
4801
4802    /**
4803     * Track a motion scroll
4804     *
4805     * @param deltaY Amount to offset mMotionView. This is the accumulated delta since the motion
4806     *        began. Positive numbers mean the user's finger is moving down the screen.
4807     * @param incrementalDeltaY Change in deltaY from the previous event.
4808     * @return true if we're already at the beginning/end of the list and have nothing to do.
4809     */
4810    boolean trackMotionScroll(int deltaY, int incrementalDeltaY) {
4811        final int childCount = getChildCount();
4812        if (childCount == 0) {
4813            return true;
4814        }
4815
4816        final int firstTop = getChildAt(0).getTop();
4817        final int lastBottom = getChildAt(childCount - 1).getBottom();
4818
4819        final Rect listPadding = mListPadding;
4820
4821        // "effective padding" In this case is the amount of padding that affects
4822        // how much space should not be filled by items. If we don't clip to padding
4823        // there is no effective padding.
4824        int effectivePaddingTop = 0;
4825        int effectivePaddingBottom = 0;
4826        if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
4827            effectivePaddingTop = listPadding.top;
4828            effectivePaddingBottom = listPadding.bottom;
4829        }
4830
4831         // FIXME account for grid vertical spacing too?
4832        final int spaceAbove = effectivePaddingTop - firstTop;
4833        final int end = getHeight() - effectivePaddingBottom;
4834        final int spaceBelow = lastBottom - end;
4835
4836        final int height = getHeight() - mPaddingBottom - mPaddingTop;
4837        if (deltaY < 0) {
4838            deltaY = Math.max(-(height - 1), deltaY);
4839        } else {
4840            deltaY = Math.min(height - 1, deltaY);
4841        }
4842
4843        if (incrementalDeltaY < 0) {
4844            incrementalDeltaY = Math.max(-(height - 1), incrementalDeltaY);
4845        } else {
4846            incrementalDeltaY = Math.min(height - 1, incrementalDeltaY);
4847        }
4848
4849        final int firstPosition = mFirstPosition;
4850
4851        // Update our guesses for where the first and last views are
4852        if (firstPosition == 0) {
4853            mFirstPositionDistanceGuess = firstTop - listPadding.top;
4854        } else {
4855            mFirstPositionDistanceGuess += incrementalDeltaY;
4856        }
4857        if (firstPosition + childCount == mItemCount) {
4858            mLastPositionDistanceGuess = lastBottom + listPadding.bottom;
4859        } else {
4860            mLastPositionDistanceGuess += incrementalDeltaY;
4861        }
4862
4863        final boolean cannotScrollDown = (firstPosition == 0 &&
4864                firstTop >= listPadding.top && incrementalDeltaY >= 0);
4865        final boolean cannotScrollUp = (firstPosition + childCount == mItemCount &&
4866                lastBottom <= getHeight() - listPadding.bottom && incrementalDeltaY <= 0);
4867
4868        if (cannotScrollDown || cannotScrollUp) {
4869            return incrementalDeltaY != 0;
4870        }
4871
4872        final boolean down = incrementalDeltaY < 0;
4873
4874        final boolean inTouchMode = isInTouchMode();
4875        if (inTouchMode) {
4876            hideSelector();
4877        }
4878
4879        final int headerViewsCount = getHeaderViewsCount();
4880        final int footerViewsStart = mItemCount - getFooterViewsCount();
4881
4882        int start = 0;
4883        int count = 0;
4884
4885        if (down) {
4886            int top = -incrementalDeltaY;
4887            if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
4888                top += listPadding.top;
4889            }
4890            for (int i = 0; i < childCount; i++) {
4891                final View child = getChildAt(i);
4892                if (child.getBottom() >= top) {
4893                    break;
4894                } else {
4895                    count++;
4896                    int position = firstPosition + i;
4897                    if (position >= headerViewsCount && position < footerViewsStart) {
4898                        // The view will be rebound to new data, clear any
4899                        // system-managed transient state.
4900                        if (child.isAccessibilityFocused()) {
4901                            child.clearAccessibilityFocus();
4902                        }
4903                        mRecycler.addScrapView(child, position);
4904                    }
4905                }
4906            }
4907        } else {
4908            int bottom = getHeight() - incrementalDeltaY;
4909            if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
4910                bottom -= listPadding.bottom;
4911            }
4912            for (int i = childCount - 1; i >= 0; i--) {
4913                final View child = getChildAt(i);
4914                if (child.getTop() <= bottom) {
4915                    break;
4916                } else {
4917                    start = i;
4918                    count++;
4919                    int position = firstPosition + i;
4920                    if (position >= headerViewsCount && position < footerViewsStart) {
4921                        // The view will be rebound to new data, clear any
4922                        // system-managed transient state.
4923                        if (child.isAccessibilityFocused()) {
4924                            child.clearAccessibilityFocus();
4925                        }
4926                        mRecycler.addScrapView(child, position);
4927                    }
4928                }
4929            }
4930        }
4931
4932        mMotionViewNewTop = mMotionViewOriginalTop + deltaY;
4933
4934        mBlockLayoutRequests = true;
4935
4936        if (count > 0) {
4937            detachViewsFromParent(start, count);
4938            mRecycler.removeSkippedScrap();
4939        }
4940
4941        // invalidate before moving the children to avoid unnecessary invalidate
4942        // calls to bubble up from the children all the way to the top
4943        if (!awakenScrollBars()) {
4944           invalidate();
4945        }
4946
4947        offsetChildrenTopAndBottom(incrementalDeltaY);
4948
4949        if (down) {
4950            mFirstPosition += count;
4951        }
4952
4953        final int absIncrementalDeltaY = Math.abs(incrementalDeltaY);
4954        if (spaceAbove < absIncrementalDeltaY || spaceBelow < absIncrementalDeltaY) {
4955            fillGap(down);
4956        }
4957
4958        if (!inTouchMode && mSelectedPosition != INVALID_POSITION) {
4959            final int childIndex = mSelectedPosition - mFirstPosition;
4960            if (childIndex >= 0 && childIndex < getChildCount()) {
4961                positionSelector(mSelectedPosition, getChildAt(childIndex));
4962            }
4963        } else if (mSelectorPosition != INVALID_POSITION) {
4964            final int childIndex = mSelectorPosition - mFirstPosition;
4965            if (childIndex >= 0 && childIndex < getChildCount()) {
4966                positionSelector(INVALID_POSITION, getChildAt(childIndex));
4967            }
4968        } else {
4969            mSelectorRect.setEmpty();
4970        }
4971
4972        mBlockLayoutRequests = false;
4973
4974        invokeOnItemScrollListener();
4975
4976        return false;
4977    }
4978
4979    /**
4980     * Returns the number of header views in the list. Header views are special views
4981     * at the top of the list that should not be recycled during a layout.
4982     *
4983     * @return The number of header views, 0 in the default implementation.
4984     */
4985    int getHeaderViewsCount() {
4986        return 0;
4987    }
4988
4989    /**
4990     * Returns the number of footer views in the list. Footer views are special views
4991     * at the bottom of the list that should not be recycled during a layout.
4992     *
4993     * @return The number of footer views, 0 in the default implementation.
4994     */
4995    int getFooterViewsCount() {
4996        return 0;
4997    }
4998
4999    /**
5000     * Fills the gap left open by a touch-scroll. During a touch scroll, children that
5001     * remain on screen are shifted and the other ones are discarded. The role of this
5002     * method is to fill the gap thus created by performing a partial layout in the
5003     * empty space.
5004     *
5005     * @param down true if the scroll is going down, false if it is going up
5006     */
5007    abstract void fillGap(boolean down);
5008
5009    void hideSelector() {
5010        if (mSelectedPosition != INVALID_POSITION) {
5011            if (mLayoutMode != LAYOUT_SPECIFIC) {
5012                mResurrectToPosition = mSelectedPosition;
5013            }
5014            if (mNextSelectedPosition >= 0 && mNextSelectedPosition != mSelectedPosition) {
5015                mResurrectToPosition = mNextSelectedPosition;
5016            }
5017            setSelectedPositionInt(INVALID_POSITION);
5018            setNextSelectedPositionInt(INVALID_POSITION);
5019            mSelectedTop = 0;
5020        }
5021    }
5022
5023    /**
5024     * @return A position to select. First we try mSelectedPosition. If that has been clobbered by
5025     * entering touch mode, we then try mResurrectToPosition. Values are pinned to the range
5026     * of items available in the adapter
5027     */
5028    int reconcileSelectedPosition() {
5029        int position = mSelectedPosition;
5030        if (position < 0) {
5031            position = mResurrectToPosition;
5032        }
5033        position = Math.max(0, position);
5034        position = Math.min(position, mItemCount - 1);
5035        return position;
5036    }
5037
5038    /**
5039     * Find the row closest to y. This row will be used as the motion row when scrolling
5040     *
5041     * @param y Where the user touched
5042     * @return The position of the first (or only) item in the row containing y
5043     */
5044    abstract int findMotionRow(int y);
5045
5046    /**
5047     * Find the row closest to y. This row will be used as the motion row when scrolling.
5048     *
5049     * @param y Where the user touched
5050     * @return The position of the first (or only) item in the row closest to y
5051     */
5052    int findClosestMotionRow(int y) {
5053        final int childCount = getChildCount();
5054        if (childCount == 0) {
5055            return INVALID_POSITION;
5056        }
5057
5058        final int motionRow = findMotionRow(y);
5059        return motionRow != INVALID_POSITION ? motionRow : mFirstPosition + childCount - 1;
5060    }
5061
5062    /**
5063     * Causes all the views to be rebuilt and redrawn.
5064     */
5065    public void invalidateViews() {
5066        mDataChanged = true;
5067        rememberSyncState();
5068        requestLayout();
5069        invalidate();
5070    }
5071
5072    /**
5073     * If there is a selection returns false.
5074     * Otherwise resurrects the selection and returns true if resurrected.
5075     */
5076    boolean resurrectSelectionIfNeeded() {
5077        if (mSelectedPosition < 0 && resurrectSelection()) {
5078            updateSelectorState();
5079            return true;
5080        }
5081        return false;
5082    }
5083
5084    /**
5085     * Makes the item at the supplied position selected.
5086     *
5087     * @param position the position of the new selection
5088     */
5089    abstract void setSelectionInt(int position);
5090
5091    /**
5092     * Attempt to bring the selection back if the user is switching from touch
5093     * to trackball mode
5094     * @return Whether selection was set to something.
5095     */
5096    boolean resurrectSelection() {
5097        final int childCount = getChildCount();
5098
5099        if (childCount <= 0) {
5100            return false;
5101        }
5102
5103        int selectedTop = 0;
5104        int selectedPos;
5105        int childrenTop = mListPadding.top;
5106        int childrenBottom = mBottom - mTop - mListPadding.bottom;
5107        final int firstPosition = mFirstPosition;
5108        final int toPosition = mResurrectToPosition;
5109        boolean down = true;
5110
5111        if (toPosition >= firstPosition && toPosition < firstPosition + childCount) {
5112            selectedPos = toPosition;
5113
5114            final View selected = getChildAt(selectedPos - mFirstPosition);
5115            selectedTop = selected.getTop();
5116            int selectedBottom = selected.getBottom();
5117
5118            // We are scrolled, don't get in the fade
5119            if (selectedTop < childrenTop) {
5120                selectedTop = childrenTop + getVerticalFadingEdgeLength();
5121            } else if (selectedBottom > childrenBottom) {
5122                selectedTop = childrenBottom - selected.getMeasuredHeight()
5123                        - getVerticalFadingEdgeLength();
5124            }
5125        } else {
5126            if (toPosition < firstPosition) {
5127                // Default to selecting whatever is first
5128                selectedPos = firstPosition;
5129                for (int i = 0; i < childCount; i++) {
5130                    final View v = getChildAt(i);
5131                    final int top = v.getTop();
5132
5133                    if (i == 0) {
5134                        // Remember the position of the first item
5135                        selectedTop = top;
5136                        // See if we are scrolled at all
5137                        if (firstPosition > 0 || top < childrenTop) {
5138                            // If we are scrolled, don't select anything that is
5139                            // in the fade region
5140                            childrenTop += getVerticalFadingEdgeLength();
5141                        }
5142                    }
5143                    if (top >= childrenTop) {
5144                        // Found a view whose top is fully visisble
5145                        selectedPos = firstPosition + i;
5146                        selectedTop = top;
5147                        break;
5148                    }
5149                }
5150            } else {
5151                final int itemCount = mItemCount;
5152                down = false;
5153                selectedPos = firstPosition + childCount - 1;
5154
5155                for (int i = childCount - 1; i >= 0; i--) {
5156                    final View v = getChildAt(i);
5157                    final int top = v.getTop();
5158                    final int bottom = v.getBottom();
5159
5160                    if (i == childCount - 1) {
5161                        selectedTop = top;
5162                        if (firstPosition + childCount < itemCount || bottom > childrenBottom) {
5163                            childrenBottom -= getVerticalFadingEdgeLength();
5164                        }
5165                    }
5166
5167                    if (bottom <= childrenBottom) {
5168                        selectedPos = firstPosition + i;
5169                        selectedTop = top;
5170                        break;
5171                    }
5172                }
5173            }
5174        }
5175
5176        mResurrectToPosition = INVALID_POSITION;
5177        removeCallbacks(mFlingRunnable);
5178        if (mPositionScroller != null) {
5179            mPositionScroller.stop();
5180        }
5181        mTouchMode = TOUCH_MODE_REST;
5182        clearScrollingCache();
5183        mSpecificTop = selectedTop;
5184        selectedPos = lookForSelectablePosition(selectedPos, down);
5185        if (selectedPos >= firstPosition && selectedPos <= getLastVisiblePosition()) {
5186            mLayoutMode = LAYOUT_SPECIFIC;
5187            updateSelectorState();
5188            setSelectionInt(selectedPos);
5189            invokeOnItemScrollListener();
5190        } else {
5191            selectedPos = INVALID_POSITION;
5192        }
5193        reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
5194
5195        return selectedPos >= 0;
5196    }
5197
5198    void confirmCheckedPositionsById() {
5199        // Clear out the positional check states, we'll rebuild it below from IDs.
5200        mCheckStates.clear();
5201
5202        boolean checkedCountChanged = false;
5203        for (int checkedIndex = 0; checkedIndex < mCheckedIdStates.size(); checkedIndex++) {
5204            final long id = mCheckedIdStates.keyAt(checkedIndex);
5205            final int lastPos = mCheckedIdStates.valueAt(checkedIndex);
5206
5207            final long lastPosId = mAdapter.getItemId(lastPos);
5208            if (id != lastPosId) {
5209                // Look around to see if the ID is nearby. If not, uncheck it.
5210                final int start = Math.max(0, lastPos - CHECK_POSITION_SEARCH_DISTANCE);
5211                final int end = Math.min(lastPos + CHECK_POSITION_SEARCH_DISTANCE, mItemCount);
5212                boolean found = false;
5213                for (int searchPos = start; searchPos < end; searchPos++) {
5214                    final long searchId = mAdapter.getItemId(searchPos);
5215                    if (id == searchId) {
5216                        found = true;
5217                        mCheckStates.put(searchPos, true);
5218                        mCheckedIdStates.setValueAt(checkedIndex, searchPos);
5219                        break;
5220                    }
5221                }
5222
5223                if (!found) {
5224                    mCheckedIdStates.delete(id);
5225                    checkedIndex--;
5226                    mCheckedItemCount--;
5227                    checkedCountChanged = true;
5228                    if (mChoiceActionMode != null && mMultiChoiceModeCallback != null) {
5229                        mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode,
5230                                lastPos, id, false);
5231                    }
5232                }
5233            } else {
5234                mCheckStates.put(lastPos, true);
5235            }
5236        }
5237
5238        if (checkedCountChanged && mChoiceActionMode != null) {
5239            mChoiceActionMode.invalidate();
5240        }
5241    }
5242
5243    @Override
5244    protected void handleDataChanged() {
5245        int count = mItemCount;
5246        int lastHandledItemCount = mLastHandledItemCount;
5247        mLastHandledItemCount = mItemCount;
5248
5249        if (mChoiceMode != CHOICE_MODE_NONE && mAdapter != null && mAdapter.hasStableIds()) {
5250            confirmCheckedPositionsById();
5251        }
5252
5253        // TODO: In the future we can recycle these views based on stable ID instead.
5254        mRecycler.clearTransientStateViews();
5255
5256        if (count > 0) {
5257            int newPos;
5258            int selectablePos;
5259
5260            // Find the row we are supposed to sync to
5261            if (mNeedSync) {
5262                // Update this first, since setNextSelectedPositionInt inspects it
5263                mNeedSync = false;
5264                mPendingSync = null;
5265
5266                if (mTranscriptMode == TRANSCRIPT_MODE_ALWAYS_SCROLL) {
5267                    mLayoutMode = LAYOUT_FORCE_BOTTOM;
5268                    return;
5269                } else if (mTranscriptMode == TRANSCRIPT_MODE_NORMAL) {
5270                    if (mForceTranscriptScroll) {
5271                        mForceTranscriptScroll = false;
5272                        mLayoutMode = LAYOUT_FORCE_BOTTOM;
5273                        return;
5274                    }
5275                    final int childCount = getChildCount();
5276                    final int listBottom = getHeight() - getPaddingBottom();
5277                    final View lastChild = getChildAt(childCount - 1);
5278                    final int lastBottom = lastChild != null ? lastChild.getBottom() : listBottom;
5279                    if (mFirstPosition + childCount >= lastHandledItemCount &&
5280                            lastBottom <= listBottom) {
5281                        mLayoutMode = LAYOUT_FORCE_BOTTOM;
5282                        return;
5283                    }
5284                    // Something new came in and we didn't scroll; give the user a clue that
5285                    // there's something new.
5286                    awakenScrollBars();
5287                }
5288
5289                switch (mSyncMode) {
5290                case SYNC_SELECTED_POSITION:
5291                    if (isInTouchMode()) {
5292                        // We saved our state when not in touch mode. (We know this because
5293                        // mSyncMode is SYNC_SELECTED_POSITION.) Now we are trying to
5294                        // restore in touch mode. Just leave mSyncPosition as it is (possibly
5295                        // adjusting if the available range changed) and return.
5296                        mLayoutMode = LAYOUT_SYNC;
5297                        mSyncPosition = Math.min(Math.max(0, mSyncPosition), count - 1);
5298
5299                        return;
5300                    } else {
5301                        // See if we can find a position in the new data with the same
5302                        // id as the old selection. This will change mSyncPosition.
5303                        newPos = findSyncPosition();
5304                        if (newPos >= 0) {
5305                            // Found it. Now verify that new selection is still selectable
5306                            selectablePos = lookForSelectablePosition(newPos, true);
5307                            if (selectablePos == newPos) {
5308                                // Same row id is selected
5309                                mSyncPosition = newPos;
5310
5311                                if (mSyncHeight == getHeight()) {
5312                                    // If we are at the same height as when we saved state, try
5313                                    // to restore the scroll position too.
5314                                    mLayoutMode = LAYOUT_SYNC;
5315                                } else {
5316                                    // We are not the same height as when the selection was saved, so
5317                                    // don't try to restore the exact position
5318                                    mLayoutMode = LAYOUT_SET_SELECTION;
5319                                }
5320
5321                                // Restore selection
5322                                setNextSelectedPositionInt(newPos);
5323                                return;
5324                            }
5325                        }
5326                    }
5327                    break;
5328                case SYNC_FIRST_POSITION:
5329                    // Leave mSyncPosition as it is -- just pin to available range
5330                    mLayoutMode = LAYOUT_SYNC;
5331                    mSyncPosition = Math.min(Math.max(0, mSyncPosition), count - 1);
5332
5333                    return;
5334                }
5335            }
5336
5337            if (!isInTouchMode()) {
5338                // We couldn't find matching data -- try to use the same position
5339                newPos = getSelectedItemPosition();
5340
5341                // Pin position to the available range
5342                if (newPos >= count) {
5343                    newPos = count - 1;
5344                }
5345                if (newPos < 0) {
5346                    newPos = 0;
5347                }
5348
5349                // Make sure we select something selectable -- first look down
5350                selectablePos = lookForSelectablePosition(newPos, true);
5351
5352                if (selectablePos >= 0) {
5353                    setNextSelectedPositionInt(selectablePos);
5354                    return;
5355                } else {
5356                    // Looking down didn't work -- try looking up
5357                    selectablePos = lookForSelectablePosition(newPos, false);
5358                    if (selectablePos >= 0) {
5359                        setNextSelectedPositionInt(selectablePos);
5360                        return;
5361                    }
5362                }
5363            } else {
5364
5365                // We already know where we want to resurrect the selection
5366                if (mResurrectToPosition >= 0) {
5367                    return;
5368                }
5369            }
5370
5371        }
5372
5373        // Nothing is selected. Give up and reset everything.
5374        mLayoutMode = mStackFromBottom ? LAYOUT_FORCE_BOTTOM : LAYOUT_FORCE_TOP;
5375        mSelectedPosition = INVALID_POSITION;
5376        mSelectedRowId = INVALID_ROW_ID;
5377        mNextSelectedPosition = INVALID_POSITION;
5378        mNextSelectedRowId = INVALID_ROW_ID;
5379        mNeedSync = false;
5380        mPendingSync = null;
5381        mSelectorPosition = INVALID_POSITION;
5382        checkSelectionChanged();
5383    }
5384
5385    @Override
5386    protected void onDisplayHint(int hint) {
5387        super.onDisplayHint(hint);
5388        switch (hint) {
5389            case INVISIBLE:
5390                if (mPopup != null && mPopup.isShowing()) {
5391                    dismissPopup();
5392                }
5393                break;
5394            case VISIBLE:
5395                if (mFiltered && mPopup != null && !mPopup.isShowing()) {
5396                    showPopup();
5397                }
5398                break;
5399        }
5400        mPopupHidden = hint == INVISIBLE;
5401    }
5402
5403    /**
5404     * Removes the filter window
5405     */
5406    private void dismissPopup() {
5407        if (mPopup != null) {
5408            mPopup.dismiss();
5409        }
5410    }
5411
5412    /**
5413     * Shows the filter window
5414     */
5415    private void showPopup() {
5416        // Make sure we have a window before showing the popup
5417        if (getWindowVisibility() == View.VISIBLE) {
5418            createTextFilter(true);
5419            positionPopup();
5420            // Make sure we get focus if we are showing the popup
5421            checkFocus();
5422        }
5423    }
5424
5425    private void positionPopup() {
5426        int screenHeight = getResources().getDisplayMetrics().heightPixels;
5427        final int[] xy = new int[2];
5428        getLocationOnScreen(xy);
5429        // TODO: The 20 below should come from the theme
5430        // TODO: And the gravity should be defined in the theme as well
5431        final int bottomGap = screenHeight - xy[1] - getHeight() + (int) (mDensityScale * 20);
5432        if (!mPopup.isShowing()) {
5433            mPopup.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,
5434                    xy[0], bottomGap);
5435        } else {
5436            mPopup.update(xy[0], bottomGap, -1, -1);
5437        }
5438    }
5439
5440    /**
5441     * What is the distance between the source and destination rectangles given the direction of
5442     * focus navigation between them? The direction basically helps figure out more quickly what is
5443     * self evident by the relationship between the rects...
5444     *
5445     * @param source the source rectangle
5446     * @param dest the destination rectangle
5447     * @param direction the direction
5448     * @return the distance between the rectangles
5449     */
5450    static int getDistance(Rect source, Rect dest, int direction) {
5451        int sX, sY; // source x, y
5452        int dX, dY; // dest x, y
5453        switch (direction) {
5454        case View.FOCUS_RIGHT:
5455            sX = source.right;
5456            sY = source.top + source.height() / 2;
5457            dX = dest.left;
5458            dY = dest.top + dest.height() / 2;
5459            break;
5460        case View.FOCUS_DOWN:
5461            sX = source.left + source.width() / 2;
5462            sY = source.bottom;
5463            dX = dest.left + dest.width() / 2;
5464            dY = dest.top;
5465            break;
5466        case View.FOCUS_LEFT:
5467            sX = source.left;
5468            sY = source.top + source.height() / 2;
5469            dX = dest.right;
5470            dY = dest.top + dest.height() / 2;
5471            break;
5472        case View.FOCUS_UP:
5473            sX = source.left + source.width() / 2;
5474            sY = source.top;
5475            dX = dest.left + dest.width() / 2;
5476            dY = dest.bottom;
5477            break;
5478        case View.FOCUS_FORWARD:
5479        case View.FOCUS_BACKWARD:
5480            sX = source.right + source.width() / 2;
5481            sY = source.top + source.height() / 2;
5482            dX = dest.left + dest.width() / 2;
5483            dY = dest.top + dest.height() / 2;
5484            break;
5485        default:
5486            throw new IllegalArgumentException("direction must be one of "
5487                    + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, "
5488                    + "FOCUS_FORWARD, FOCUS_BACKWARD}.");
5489        }
5490        int deltaX = dX - sX;
5491        int deltaY = dY - sY;
5492        return deltaY * deltaY + deltaX * deltaX;
5493    }
5494
5495    @Override
5496    protected boolean isInFilterMode() {
5497        return mFiltered;
5498    }
5499
5500    /**
5501     * Sends a key to the text filter window
5502     *
5503     * @param keyCode The keycode for the event
5504     * @param event The actual key event
5505     *
5506     * @return True if the text filter handled the event, false otherwise.
5507     */
5508    boolean sendToTextFilter(int keyCode, int count, KeyEvent event) {
5509        if (!acceptFilter()) {
5510            return false;
5511        }
5512
5513        boolean handled = false;
5514        boolean okToSend = true;
5515        switch (keyCode) {
5516        case KeyEvent.KEYCODE_DPAD_UP:
5517        case KeyEvent.KEYCODE_DPAD_DOWN:
5518        case KeyEvent.KEYCODE_DPAD_LEFT:
5519        case KeyEvent.KEYCODE_DPAD_RIGHT:
5520        case KeyEvent.KEYCODE_DPAD_CENTER:
5521        case KeyEvent.KEYCODE_ENTER:
5522            okToSend = false;
5523            break;
5524        case KeyEvent.KEYCODE_BACK:
5525            if (mFiltered && mPopup != null && mPopup.isShowing()) {
5526                if (event.getAction() == KeyEvent.ACTION_DOWN
5527                        && event.getRepeatCount() == 0) {
5528                    KeyEvent.DispatcherState state = getKeyDispatcherState();
5529                    if (state != null) {
5530                        state.startTracking(event, this);
5531                    }
5532                    handled = true;
5533                } else if (event.getAction() == KeyEvent.ACTION_UP
5534                        && event.isTracking() && !event.isCanceled()) {
5535                    handled = true;
5536                    mTextFilter.setText("");
5537                }
5538            }
5539            okToSend = false;
5540            break;
5541        case KeyEvent.KEYCODE_SPACE:
5542            // Only send spaces once we are filtered
5543            okToSend = mFiltered;
5544            break;
5545        }
5546
5547        if (okToSend) {
5548            createTextFilter(true);
5549
5550            KeyEvent forwardEvent = event;
5551            if (forwardEvent.getRepeatCount() > 0) {
5552                forwardEvent = KeyEvent.changeTimeRepeat(event, event.getEventTime(), 0);
5553            }
5554
5555            int action = event.getAction();
5556            switch (action) {
5557                case KeyEvent.ACTION_DOWN:
5558                    handled = mTextFilter.onKeyDown(keyCode, forwardEvent);
5559                    break;
5560
5561                case KeyEvent.ACTION_UP:
5562                    handled = mTextFilter.onKeyUp(keyCode, forwardEvent);
5563                    break;
5564
5565                case KeyEvent.ACTION_MULTIPLE:
5566                    handled = mTextFilter.onKeyMultiple(keyCode, count, event);
5567                    break;
5568            }
5569        }
5570        return handled;
5571    }
5572
5573    /**
5574     * Return an InputConnection for editing of the filter text.
5575     */
5576    @Override
5577    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5578        if (isTextFilterEnabled()) {
5579            if (mPublicInputConnection == null) {
5580                mDefInputConnection = new BaseInputConnection(this, false);
5581                mPublicInputConnection = new InputConnectionWrapper(outAttrs);
5582            }
5583            outAttrs.inputType = EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_FILTER;
5584            outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
5585            return mPublicInputConnection;
5586        }
5587        return null;
5588    }
5589
5590    private class InputConnectionWrapper implements InputConnection {
5591        private final EditorInfo mOutAttrs;
5592        private InputConnection mTarget;
5593
5594        public InputConnectionWrapper(EditorInfo outAttrs) {
5595            mOutAttrs = outAttrs;
5596        }
5597
5598        private InputConnection getTarget() {
5599            if (mTarget == null) {
5600                mTarget = getTextFilterInput().onCreateInputConnection(mOutAttrs);
5601            }
5602            return mTarget;
5603        }
5604
5605        @Override
5606        public boolean reportFullscreenMode(boolean enabled) {
5607            // Use our own input connection, since it is
5608            // the "real" one the IME is talking with.
5609            return mDefInputConnection.reportFullscreenMode(enabled);
5610        }
5611
5612        @Override
5613        public boolean performEditorAction(int editorAction) {
5614            // The editor is off in its own window; we need to be
5615            // the one that does this.
5616            if (editorAction == EditorInfo.IME_ACTION_DONE) {
5617                InputMethodManager imm = (InputMethodManager)
5618                        getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
5619                if (imm != null) {
5620                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
5621                }
5622                return true;
5623            }
5624            return false;
5625        }
5626
5627        @Override
5628        public boolean sendKeyEvent(KeyEvent event) {
5629            // Use our own input connection, since the filter
5630            // text view may not be shown in a window so has
5631            // no ViewAncestor to dispatch events with.
5632            return mDefInputConnection.sendKeyEvent(event);
5633        }
5634
5635        @Override
5636        public CharSequence getTextBeforeCursor(int n, int flags) {
5637            if (mTarget == null) return "";
5638            return mTarget.getTextBeforeCursor(n, flags);
5639        }
5640
5641        @Override
5642        public CharSequence getTextAfterCursor(int n, int flags) {
5643            if (mTarget == null) return "";
5644            return mTarget.getTextAfterCursor(n, flags);
5645        }
5646
5647        @Override
5648        public CharSequence getSelectedText(int flags) {
5649            if (mTarget == null) return "";
5650            return mTarget.getSelectedText(flags);
5651        }
5652
5653        @Override
5654        public int getCursorCapsMode(int reqModes) {
5655            if (mTarget == null) return InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
5656            return mTarget.getCursorCapsMode(reqModes);
5657        }
5658
5659        @Override
5660        public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) {
5661            return getTarget().getExtractedText(request, flags);
5662        }
5663
5664        @Override
5665        public boolean deleteSurroundingText(int beforeLength, int afterLength) {
5666            return getTarget().deleteSurroundingText(beforeLength, afterLength);
5667        }
5668
5669        @Override
5670        public boolean setComposingText(CharSequence text, int newCursorPosition) {
5671            return getTarget().setComposingText(text, newCursorPosition);
5672        }
5673
5674        @Override
5675        public boolean setComposingRegion(int start, int end) {
5676            return getTarget().setComposingRegion(start, end);
5677        }
5678
5679        @Override
5680        public boolean finishComposingText() {
5681            return mTarget == null || mTarget.finishComposingText();
5682        }
5683
5684        @Override
5685        public boolean commitText(CharSequence text, int newCursorPosition) {
5686            return getTarget().commitText(text, newCursorPosition);
5687        }
5688
5689        @Override
5690        public boolean commitCompletion(CompletionInfo text) {
5691            return getTarget().commitCompletion(text);
5692        }
5693
5694        @Override
5695        public boolean commitCorrection(CorrectionInfo correctionInfo) {
5696            return getTarget().commitCorrection(correctionInfo);
5697        }
5698
5699        @Override
5700        public boolean setSelection(int start, int end) {
5701            return getTarget().setSelection(start, end);
5702        }
5703
5704        @Override
5705        public boolean performContextMenuAction(int id) {
5706            return getTarget().performContextMenuAction(id);
5707        }
5708
5709        @Override
5710        public boolean beginBatchEdit() {
5711            return getTarget().beginBatchEdit();
5712        }
5713
5714        @Override
5715        public boolean endBatchEdit() {
5716            return getTarget().endBatchEdit();
5717        }
5718
5719        @Override
5720        public boolean clearMetaKeyStates(int states) {
5721            return getTarget().clearMetaKeyStates(states);
5722        }
5723
5724        @Override
5725        public boolean performPrivateCommand(String action, Bundle data) {
5726            return getTarget().performPrivateCommand(action, data);
5727        }
5728
5729        @Override
5730        public boolean requestCursorUpdates(int cursorUpdateMode) {
5731            return getTarget().requestCursorUpdates(cursorUpdateMode);
5732        }
5733    }
5734
5735    /**
5736     * For filtering we proxy an input connection to an internal text editor,
5737     * and this allows the proxying to happen.
5738     */
5739    @Override
5740    public boolean checkInputConnectionProxy(View view) {
5741        return view == mTextFilter;
5742    }
5743
5744    /**
5745     * Creates the window for the text filter and populates it with an EditText field;
5746     *
5747     * @param animateEntrance true if the window should appear with an animation
5748     */
5749    private void createTextFilter(boolean animateEntrance) {
5750        if (mPopup == null) {
5751            PopupWindow p = new PopupWindow(getContext());
5752            p.setFocusable(false);
5753            p.setTouchable(false);
5754            p.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
5755            p.setContentView(getTextFilterInput());
5756            p.setWidth(LayoutParams.WRAP_CONTENT);
5757            p.setHeight(LayoutParams.WRAP_CONTENT);
5758            p.setBackgroundDrawable(null);
5759            mPopup = p;
5760            getViewTreeObserver().addOnGlobalLayoutListener(this);
5761            mGlobalLayoutListenerAddedFilter = true;
5762        }
5763        if (animateEntrance) {
5764            mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilter);
5765        } else {
5766            mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilterRestore);
5767        }
5768    }
5769
5770    private EditText getTextFilterInput() {
5771        if (mTextFilter == null) {
5772            final LayoutInflater layoutInflater = LayoutInflater.from(getContext());
5773            mTextFilter = (EditText) layoutInflater.inflate(
5774                    com.android.internal.R.layout.typing_filter, null);
5775            // For some reason setting this as the "real" input type changes
5776            // the text view in some way that it doesn't work, and I don't
5777            // want to figure out why this is.
5778            mTextFilter.setRawInputType(EditorInfo.TYPE_CLASS_TEXT
5779                    | EditorInfo.TYPE_TEXT_VARIATION_FILTER);
5780            mTextFilter.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
5781            mTextFilter.addTextChangedListener(this);
5782        }
5783        return mTextFilter;
5784    }
5785
5786    /**
5787     * Clear the text filter.
5788     */
5789    public void clearTextFilter() {
5790        if (mFiltered) {
5791            getTextFilterInput().setText("");
5792            mFiltered = false;
5793            if (mPopup != null && mPopup.isShowing()) {
5794                dismissPopup();
5795            }
5796        }
5797    }
5798
5799    /**
5800     * Returns if the ListView currently has a text filter.
5801     */
5802    public boolean hasTextFilter() {
5803        return mFiltered;
5804    }
5805
5806    @Override
5807    public void onGlobalLayout() {
5808        if (isShown()) {
5809            // Show the popup if we are filtered
5810            if (mFiltered && mPopup != null && !mPopup.isShowing() && !mPopupHidden) {
5811                showPopup();
5812            }
5813        } else {
5814            // Hide the popup when we are no longer visible
5815            if (mPopup != null && mPopup.isShowing()) {
5816                dismissPopup();
5817            }
5818        }
5819
5820    }
5821
5822    /**
5823     * For our text watcher that is associated with the text filter.  Does
5824     * nothing.
5825     */
5826    @Override
5827    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
5828    }
5829
5830    /**
5831     * For our text watcher that is associated with the text filter. Performs
5832     * the actual filtering as the text changes, and takes care of hiding and
5833     * showing the popup displaying the currently entered filter text.
5834     */
5835    @Override
5836    public void onTextChanged(CharSequence s, int start, int before, int count) {
5837        if (isTextFilterEnabled()) {
5838            createTextFilter(true);
5839            int length = s.length();
5840            boolean showing = mPopup.isShowing();
5841            if (!showing && length > 0) {
5842                // Show the filter popup if necessary
5843                showPopup();
5844                mFiltered = true;
5845            } else if (showing && length == 0) {
5846                // Remove the filter popup if the user has cleared all text
5847                dismissPopup();
5848                mFiltered = false;
5849            }
5850            if (mAdapter instanceof Filterable) {
5851                Filter f = ((Filterable) mAdapter).getFilter();
5852                // Filter should not be null when we reach this part
5853                if (f != null) {
5854                    f.filter(s, this);
5855                } else {
5856                    throw new IllegalStateException("You cannot call onTextChanged with a non "
5857                            + "filterable adapter");
5858                }
5859            }
5860        }
5861    }
5862
5863    /**
5864     * For our text watcher that is associated with the text filter.  Does
5865     * nothing.
5866     */
5867    @Override
5868    public void afterTextChanged(Editable s) {
5869    }
5870
5871    @Override
5872    public void onFilterComplete(int count) {
5873        if (mSelectedPosition < 0 && count > 0) {
5874            mResurrectToPosition = INVALID_POSITION;
5875            resurrectSelection();
5876        }
5877    }
5878
5879    @Override
5880    protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
5881        return new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
5882                ViewGroup.LayoutParams.WRAP_CONTENT, 0);
5883    }
5884
5885    @Override
5886    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
5887        return new LayoutParams(p);
5888    }
5889
5890    @Override
5891    public LayoutParams generateLayoutParams(AttributeSet attrs) {
5892        return new AbsListView.LayoutParams(getContext(), attrs);
5893    }
5894
5895    @Override
5896    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
5897        return p instanceof AbsListView.LayoutParams;
5898    }
5899
5900    /**
5901     * Puts the list or grid into transcript mode. In this mode the list or grid will always scroll
5902     * to the bottom to show new items.
5903     *
5904     * @param mode the transcript mode to set
5905     *
5906     * @see #TRANSCRIPT_MODE_DISABLED
5907     * @see #TRANSCRIPT_MODE_NORMAL
5908     * @see #TRANSCRIPT_MODE_ALWAYS_SCROLL
5909     */
5910    public void setTranscriptMode(int mode) {
5911        mTranscriptMode = mode;
5912    }
5913
5914    /**
5915     * Returns the current transcript mode.
5916     *
5917     * @return {@link #TRANSCRIPT_MODE_DISABLED}, {@link #TRANSCRIPT_MODE_NORMAL} or
5918     *         {@link #TRANSCRIPT_MODE_ALWAYS_SCROLL}
5919     */
5920    public int getTranscriptMode() {
5921        return mTranscriptMode;
5922    }
5923
5924    @Override
5925    public int getSolidColor() {
5926        return mCacheColorHint;
5927    }
5928
5929    /**
5930     * When set to a non-zero value, the cache color hint indicates that this list is always drawn
5931     * on top of a solid, single-color, opaque background.
5932     *
5933     * Zero means that what's behind this object is translucent (non solid) or is not made of a
5934     * single color. This hint will not affect any existing background drawable set on this view (
5935     * typically set via {@link #setBackgroundDrawable(Drawable)}).
5936     *
5937     * @param color The background color
5938     */
5939    public void setCacheColorHint(int color) {
5940        if (color != mCacheColorHint) {
5941            mCacheColorHint = color;
5942            int count = getChildCount();
5943            for (int i = 0; i < count; i++) {
5944                getChildAt(i).setDrawingCacheBackgroundColor(color);
5945            }
5946            mRecycler.setCacheColorHint(color);
5947        }
5948    }
5949
5950    /**
5951     * When set to a non-zero value, the cache color hint indicates that this list is always drawn
5952     * on top of a solid, single-color, opaque background
5953     *
5954     * @return The cache color hint
5955     */
5956    @ViewDebug.ExportedProperty(category = "drawing")
5957    public int getCacheColorHint() {
5958        return mCacheColorHint;
5959    }
5960
5961    /**
5962     * Move all views (excluding headers and footers) held by this AbsListView into the supplied
5963     * List. This includes views displayed on the screen as well as views stored in AbsListView's
5964     * internal view recycler.
5965     *
5966     * @param views A list into which to put the reclaimed views
5967     */
5968    public void reclaimViews(List<View> views) {
5969        int childCount = getChildCount();
5970        RecyclerListener listener = mRecycler.mRecyclerListener;
5971
5972        // Reclaim views on screen
5973        for (int i = 0; i < childCount; i++) {
5974            View child = getChildAt(i);
5975            AbsListView.LayoutParams lp = (AbsListView.LayoutParams) child.getLayoutParams();
5976            // Don't reclaim header or footer views, or views that should be ignored
5977            if (lp != null && mRecycler.shouldRecycleViewType(lp.viewType)) {
5978                views.add(child);
5979                child.setAccessibilityDelegate(null);
5980                if (listener != null) {
5981                    // Pretend they went through the scrap heap
5982                    listener.onMovedToScrapHeap(child);
5983                }
5984            }
5985        }
5986        mRecycler.reclaimScrapViews(views);
5987        removeAllViewsInLayout();
5988    }
5989
5990    private void finishGlows() {
5991        if (mEdgeGlowTop != null) {
5992            mEdgeGlowTop.finish();
5993            mEdgeGlowBottom.finish();
5994        }
5995    }
5996
5997    /**
5998     * Sets up this AbsListView to use a remote views adapter which connects to a RemoteViewsService
5999     * through the specified intent.
6000     * @param intent the intent used to identify the RemoteViewsService for the adapter to connect to.
6001     */
6002    public void setRemoteViewsAdapter(Intent intent) {
6003        // Ensure that we don't already have a RemoteViewsAdapter that is bound to an existing
6004        // service handling the specified intent.
6005        if (mRemoteAdapter != null) {
6006            Intent.FilterComparison fcNew = new Intent.FilterComparison(intent);
6007            Intent.FilterComparison fcOld = new Intent.FilterComparison(
6008                    mRemoteAdapter.getRemoteViewsServiceIntent());
6009            if (fcNew.equals(fcOld)) {
6010                return;
6011            }
6012        }
6013        mDeferNotifyDataSetChanged = false;
6014        // Otherwise, create a new RemoteViewsAdapter for binding
6015        mRemoteAdapter = new RemoteViewsAdapter(getContext(), intent, this);
6016        if (mRemoteAdapter.isDataReady()) {
6017            setAdapter(mRemoteAdapter);
6018        }
6019    }
6020
6021    /**
6022     * Sets up the onClickHandler to be used by the RemoteViewsAdapter when inflating RemoteViews
6023     *
6024     * @param handler The OnClickHandler to use when inflating RemoteViews.
6025     *
6026     * @hide
6027     */
6028    public void setRemoteViewsOnClickHandler(OnClickHandler handler) {
6029        // Ensure that we don't already have a RemoteViewsAdapter that is bound to an existing
6030        // service handling the specified intent.
6031        if (mRemoteAdapter != null) {
6032            mRemoteAdapter.setRemoteViewsOnClickHandler(handler);
6033        }
6034    }
6035
6036    /**
6037     * This defers a notifyDataSetChanged on the pending RemoteViewsAdapter if it has not
6038     * connected yet.
6039     */
6040    @Override
6041    public void deferNotifyDataSetChanged() {
6042        mDeferNotifyDataSetChanged = true;
6043    }
6044
6045    /**
6046     * Called back when the adapter connects to the RemoteViewsService.
6047     */
6048    @Override
6049    public boolean onRemoteAdapterConnected() {
6050        if (mRemoteAdapter != mAdapter) {
6051            setAdapter(mRemoteAdapter);
6052            if (mDeferNotifyDataSetChanged) {
6053                mRemoteAdapter.notifyDataSetChanged();
6054                mDeferNotifyDataSetChanged = false;
6055            }
6056            return false;
6057        } else if (mRemoteAdapter != null) {
6058            mRemoteAdapter.superNotifyDataSetChanged();
6059            return true;
6060        }
6061        return false;
6062    }
6063
6064    /**
6065     * Called back when the adapter disconnects from the RemoteViewsService.
6066     */
6067    @Override
6068    public void onRemoteAdapterDisconnected() {
6069        // If the remote adapter disconnects, we keep it around
6070        // since the currently displayed items are still cached.
6071        // Further, we want the service to eventually reconnect
6072        // when necessary, as triggered by this view requesting
6073        // items from the Adapter.
6074    }
6075
6076    /**
6077     * Hints the RemoteViewsAdapter, if it exists, about which views are currently
6078     * being displayed by the AbsListView.
6079     */
6080    void setVisibleRangeHint(int start, int end) {
6081        if (mRemoteAdapter != null) {
6082            mRemoteAdapter.setVisibleRangeHint(start, end);
6083        }
6084    }
6085
6086    /**
6087     * Sets the recycler listener to be notified whenever a View is set aside in
6088     * the recycler for later reuse. This listener can be used to free resources
6089     * associated to the View.
6090     *
6091     * @param listener The recycler listener to be notified of views set aside
6092     *        in the recycler.
6093     *
6094     * @see android.widget.AbsListView.RecycleBin
6095     * @see android.widget.AbsListView.RecyclerListener
6096     */
6097    public void setRecyclerListener(RecyclerListener listener) {
6098        mRecycler.mRecyclerListener = listener;
6099    }
6100
6101    class AdapterDataSetObserver extends AdapterView<ListAdapter>.AdapterDataSetObserver {
6102        @Override
6103        public void onChanged() {
6104            super.onChanged();
6105            if (mFastScroll != null) {
6106                mFastScroll.onSectionsChanged();
6107            }
6108        }
6109
6110        @Override
6111        public void onInvalidated() {
6112            super.onInvalidated();
6113            if (mFastScroll != null) {
6114                mFastScroll.onSectionsChanged();
6115            }
6116        }
6117    }
6118
6119    /**
6120     * A MultiChoiceModeListener receives events for {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL}.
6121     * It acts as the {@link ActionMode.Callback} for the selection mode and also receives
6122     * {@link #onItemCheckedStateChanged(ActionMode, int, long, boolean)} events when the user
6123     * selects and deselects list items.
6124     */
6125    public interface MultiChoiceModeListener extends ActionMode.Callback {
6126        /**
6127         * Called when an item is checked or unchecked during selection mode.
6128         *
6129         * @param mode The {@link ActionMode} providing the selection mode
6130         * @param position Adapter position of the item that was checked or unchecked
6131         * @param id Adapter ID of the item that was checked or unchecked
6132         * @param checked <code>true</code> if the item is now checked, <code>false</code>
6133         *                if the item is now unchecked.
6134         */
6135        public void onItemCheckedStateChanged(ActionMode mode,
6136                int position, long id, boolean checked);
6137    }
6138
6139    class MultiChoiceModeWrapper implements MultiChoiceModeListener {
6140        private MultiChoiceModeListener mWrapped;
6141
6142        public void setWrapped(MultiChoiceModeListener wrapped) {
6143            mWrapped = wrapped;
6144        }
6145
6146        public boolean hasWrappedCallback() {
6147            return mWrapped != null;
6148        }
6149
6150        @Override
6151        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
6152            if (mWrapped.onCreateActionMode(mode, menu)) {
6153                // Initialize checked graphic state?
6154                setLongClickable(false);
6155                return true;
6156            }
6157            return false;
6158        }
6159
6160        @Override
6161        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
6162            return mWrapped.onPrepareActionMode(mode, menu);
6163        }
6164
6165        @Override
6166        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
6167            return mWrapped.onActionItemClicked(mode, item);
6168        }
6169
6170        @Override
6171        public void onDestroyActionMode(ActionMode mode) {
6172            mWrapped.onDestroyActionMode(mode);
6173            mChoiceActionMode = null;
6174
6175            // Ending selection mode means deselecting everything.
6176            clearChoices();
6177
6178            mDataChanged = true;
6179            rememberSyncState();
6180            requestLayout();
6181
6182            setLongClickable(true);
6183        }
6184
6185        @Override
6186        public void onItemCheckedStateChanged(ActionMode mode,
6187                int position, long id, boolean checked) {
6188            mWrapped.onItemCheckedStateChanged(mode, position, id, checked);
6189
6190            // If there are no items selected we no longer need the selection mode.
6191            if (getCheckedItemCount() == 0) {
6192                mode.finish();
6193            }
6194        }
6195    }
6196
6197    /**
6198     * AbsListView extends LayoutParams to provide a place to hold the view type.
6199     */
6200    public static class LayoutParams extends ViewGroup.LayoutParams {
6201        /**
6202         * View type for this view, as returned by
6203         * {@link android.widget.Adapter#getItemViewType(int) }
6204         */
6205        @ViewDebug.ExportedProperty(category = "list", mapping = {
6206            @ViewDebug.IntToString(from = ITEM_VIEW_TYPE_IGNORE, to = "ITEM_VIEW_TYPE_IGNORE"),
6207            @ViewDebug.IntToString(from = ITEM_VIEW_TYPE_HEADER_OR_FOOTER, to = "ITEM_VIEW_TYPE_HEADER_OR_FOOTER")
6208        })
6209        int viewType;
6210
6211        /**
6212         * When this boolean is set, the view has been added to the AbsListView
6213         * at least once. It is used to know whether headers/footers have already
6214         * been added to the list view and whether they should be treated as
6215         * recycled views or not.
6216         */
6217        @ViewDebug.ExportedProperty(category = "list")
6218        boolean recycledHeaderFooter;
6219
6220        /**
6221         * When an AbsListView is measured with an AT_MOST measure spec, it needs
6222         * to obtain children views to measure itself. When doing so, the children
6223         * are not attached to the window, but put in the recycler which assumes
6224         * they've been attached before. Setting this flag will force the reused
6225         * view to be attached to the window rather than just attached to the
6226         * parent.
6227         */
6228        @ViewDebug.ExportedProperty(category = "list")
6229        boolean forceAdd;
6230
6231        /**
6232         * The position the view was removed from when pulled out of the
6233         * scrap heap.
6234         * @hide
6235         */
6236        int scrappedFromPosition;
6237
6238        /**
6239         * The ID the view represents
6240         */
6241        long itemId = -1;
6242
6243        public LayoutParams(Context c, AttributeSet attrs) {
6244            super(c, attrs);
6245        }
6246
6247        public LayoutParams(int w, int h) {
6248            super(w, h);
6249        }
6250
6251        public LayoutParams(int w, int h, int viewType) {
6252            super(w, h);
6253            this.viewType = viewType;
6254        }
6255
6256        public LayoutParams(ViewGroup.LayoutParams source) {
6257            super(source);
6258        }
6259    }
6260
6261    /**
6262     * A RecyclerListener is used to receive a notification whenever a View is placed
6263     * inside the RecycleBin's scrap heap. This listener is used to free resources
6264     * associated to Views placed in the RecycleBin.
6265     *
6266     * @see android.widget.AbsListView.RecycleBin
6267     * @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener)
6268     */
6269    public static interface RecyclerListener {
6270        /**
6271         * Indicates that the specified View was moved into the recycler's scrap heap.
6272         * The view is not displayed on screen any more and any expensive resource
6273         * associated with the view should be discarded.
6274         *
6275         * @param view
6276         */
6277        void onMovedToScrapHeap(View view);
6278    }
6279
6280    /**
6281     * The RecycleBin facilitates reuse of views across layouts. The RecycleBin has two levels of
6282     * storage: ActiveViews and ScrapViews. ActiveViews are those views which were onscreen at the
6283     * start of a layout. By construction, they are displaying current information. At the end of
6284     * layout, all views in ActiveViews are demoted to ScrapViews. ScrapViews are old views that
6285     * could potentially be used by the adapter to avoid allocating views unnecessarily.
6286     *
6287     * @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener)
6288     * @see android.widget.AbsListView.RecyclerListener
6289     */
6290    class RecycleBin {
6291        private RecyclerListener mRecyclerListener;
6292
6293        /**
6294         * The position of the first view stored in mActiveViews.
6295         */
6296        private int mFirstActivePosition;
6297
6298        /**
6299         * Views that were on screen at the start of layout. This array is populated at the start of
6300         * layout, and at the end of layout all view in mActiveViews are moved to mScrapViews.
6301         * Views in mActiveViews represent a contiguous range of Views, with position of the first
6302         * view store in mFirstActivePosition.
6303         */
6304        private View[] mActiveViews = new View[0];
6305
6306        /**
6307         * Unsorted views that can be used by the adapter as a convert view.
6308         */
6309        private ArrayList<View>[] mScrapViews;
6310
6311        private int mViewTypeCount;
6312
6313        private ArrayList<View> mCurrentScrap;
6314
6315        private ArrayList<View> mSkippedScrap;
6316
6317        private SparseArray<View> mTransientStateViews;
6318        private LongSparseArray<View> mTransientStateViewsById;
6319
6320        public void setViewTypeCount(int viewTypeCount) {
6321            if (viewTypeCount < 1) {
6322                throw new IllegalArgumentException("Can't have a viewTypeCount < 1");
6323            }
6324            //noinspection unchecked
6325            ArrayList<View>[] scrapViews = new ArrayList[viewTypeCount];
6326            for (int i = 0; i < viewTypeCount; i++) {
6327                scrapViews[i] = new ArrayList<View>();
6328            }
6329            mViewTypeCount = viewTypeCount;
6330            mCurrentScrap = scrapViews[0];
6331            mScrapViews = scrapViews;
6332        }
6333
6334        public void markChildrenDirty() {
6335            if (mViewTypeCount == 1) {
6336                final ArrayList<View> scrap = mCurrentScrap;
6337                final int scrapCount = scrap.size();
6338                for (int i = 0; i < scrapCount; i++) {
6339                    scrap.get(i).forceLayout();
6340                }
6341            } else {
6342                final int typeCount = mViewTypeCount;
6343                for (int i = 0; i < typeCount; i++) {
6344                    final ArrayList<View> scrap = mScrapViews[i];
6345                    final int scrapCount = scrap.size();
6346                    for (int j = 0; j < scrapCount; j++) {
6347                        scrap.get(j).forceLayout();
6348                    }
6349                }
6350            }
6351            if (mTransientStateViews != null) {
6352                final int count = mTransientStateViews.size();
6353                for (int i = 0; i < count; i++) {
6354                    mTransientStateViews.valueAt(i).forceLayout();
6355                }
6356            }
6357            if (mTransientStateViewsById != null) {
6358                final int count = mTransientStateViewsById.size();
6359                for (int i = 0; i < count; i++) {
6360                    mTransientStateViewsById.valueAt(i).forceLayout();
6361                }
6362            }
6363        }
6364
6365        public boolean shouldRecycleViewType(int viewType) {
6366            return viewType >= 0;
6367        }
6368
6369        /**
6370         * Clears the scrap heap.
6371         */
6372        void clear() {
6373            if (mViewTypeCount == 1) {
6374                final ArrayList<View> scrap = mCurrentScrap;
6375                clearScrap(scrap);
6376            } else {
6377                final int typeCount = mViewTypeCount;
6378                for (int i = 0; i < typeCount; i++) {
6379                    final ArrayList<View> scrap = mScrapViews[i];
6380                    clearScrap(scrap);
6381                }
6382            }
6383
6384            clearTransientStateViews();
6385        }
6386
6387        /**
6388         * Fill ActiveViews with all of the children of the AbsListView.
6389         *
6390         * @param childCount The minimum number of views mActiveViews should hold
6391         * @param firstActivePosition The position of the first view that will be stored in
6392         *        mActiveViews
6393         */
6394        void fillActiveViews(int childCount, int firstActivePosition) {
6395            if (mActiveViews.length < childCount) {
6396                mActiveViews = new View[childCount];
6397            }
6398            mFirstActivePosition = firstActivePosition;
6399
6400            //noinspection MismatchedReadAndWriteOfArray
6401            final View[] activeViews = mActiveViews;
6402            for (int i = 0; i < childCount; i++) {
6403                View child = getChildAt(i);
6404                AbsListView.LayoutParams lp = (AbsListView.LayoutParams) child.getLayoutParams();
6405                // Don't put header or footer views into the scrap heap
6406                if (lp != null && lp.viewType != ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
6407                    // Note:  We do place AdapterView.ITEM_VIEW_TYPE_IGNORE in active views.
6408                    //        However, we will NOT place them into scrap views.
6409                    activeViews[i] = child;
6410                }
6411            }
6412        }
6413
6414        /**
6415         * Get the view corresponding to the specified position. The view will be removed from
6416         * mActiveViews if it is found.
6417         *
6418         * @param position The position to look up in mActiveViews
6419         * @return The view if it is found, null otherwise
6420         */
6421        View getActiveView(int position) {
6422            int index = position - mFirstActivePosition;
6423            final View[] activeViews = mActiveViews;
6424            if (index >=0 && index < activeViews.length) {
6425                final View match = activeViews[index];
6426                activeViews[index] = null;
6427                return match;
6428            }
6429            return null;
6430        }
6431
6432        View getTransientStateView(int position) {
6433            if (mAdapter != null && mAdapterHasStableIds && mTransientStateViewsById != null) {
6434                long id = mAdapter.getItemId(position);
6435                View result = mTransientStateViewsById.get(id);
6436                mTransientStateViewsById.remove(id);
6437                return result;
6438            }
6439            if (mTransientStateViews != null) {
6440                final int index = mTransientStateViews.indexOfKey(position);
6441                if (index >= 0) {
6442                    View result = mTransientStateViews.valueAt(index);
6443                    mTransientStateViews.removeAt(index);
6444                    return result;
6445                }
6446            }
6447            return null;
6448        }
6449
6450        /**
6451         * Dumps and fully detaches any currently saved views with transient
6452         * state.
6453         */
6454        void clearTransientStateViews() {
6455            final SparseArray<View> viewsByPos = mTransientStateViews;
6456            if (viewsByPos != null) {
6457                final int N = viewsByPos.size();
6458                for (int i = 0; i < N; i++) {
6459                    removeDetachedView(viewsByPos.valueAt(i), false);
6460                }
6461                viewsByPos.clear();
6462            }
6463
6464            final LongSparseArray<View> viewsById = mTransientStateViewsById;
6465            if (viewsById != null) {
6466                final int N = viewsById.size();
6467                for (int i = 0; i < N; i++) {
6468                    removeDetachedView(viewsById.valueAt(i), false);
6469                }
6470                viewsById.clear();
6471            }
6472        }
6473
6474        /**
6475         * @return A view from the ScrapViews collection. These are unordered.
6476         */
6477        View getScrapView(int position) {
6478            if (mViewTypeCount == 1) {
6479                return retrieveFromScrap(mCurrentScrap, position);
6480            } else {
6481                final int whichScrap = mAdapter.getItemViewType(position);
6482                if (whichScrap >= 0 && whichScrap < mScrapViews.length) {
6483                    return retrieveFromScrap(mScrapViews[whichScrap], position);
6484                }
6485            }
6486            return null;
6487        }
6488
6489        /**
6490         * Puts a view into the list of scrap views.
6491         * <p>
6492         * If the list data hasn't changed or the adapter has stable IDs, views
6493         * with transient state will be preserved for later retrieval.
6494         *
6495         * @param scrap The view to add
6496         * @param position The view's position within its parent
6497         */
6498        void addScrapView(View scrap, int position) {
6499            final AbsListView.LayoutParams lp = (AbsListView.LayoutParams) scrap.getLayoutParams();
6500            if (lp == null) {
6501                return;
6502            }
6503
6504            lp.scrappedFromPosition = position;
6505
6506            // Remove but don't scrap header or footer views, or views that
6507            // should otherwise not be recycled.
6508            final int viewType = lp.viewType;
6509            if (!shouldRecycleViewType(viewType)) {
6510                return;
6511            }
6512
6513            scrap.dispatchStartTemporaryDetach();
6514
6515            // The the accessibility state of the view may change while temporary
6516            // detached and we do not allow detached views to fire accessibility
6517            // events. So we are announcing that the subtree changed giving a chance
6518            // to clients holding on to a view in this subtree to refresh it.
6519            notifyViewAccessibilityStateChangedIfNeeded(
6520                    AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
6521
6522            // Don't scrap views that have transient state.
6523            final boolean scrapHasTransientState = scrap.hasTransientState();
6524            if (scrapHasTransientState) {
6525                if (mAdapter != null && mAdapterHasStableIds) {
6526                    // If the adapter has stable IDs, we can reuse the view for
6527                    // the same data.
6528                    if (mTransientStateViewsById == null) {
6529                        mTransientStateViewsById = new LongSparseArray<View>();
6530                    }
6531                    mTransientStateViewsById.put(lp.itemId, scrap);
6532                } else if (!mDataChanged) {
6533                    // If the data hasn't changed, we can reuse the views at
6534                    // their old positions.
6535                    if (mTransientStateViews == null) {
6536                        mTransientStateViews = new SparseArray<View>();
6537                    }
6538                    mTransientStateViews.put(position, scrap);
6539                } else {
6540                    // Otherwise, we'll have to remove the view and start over.
6541                    if (mSkippedScrap == null) {
6542                        mSkippedScrap = new ArrayList<View>();
6543                    }
6544                    mSkippedScrap.add(scrap);
6545                }
6546            } else {
6547                if (mViewTypeCount == 1) {
6548                    mCurrentScrap.add(scrap);
6549                } else {
6550                    mScrapViews[viewType].add(scrap);
6551                }
6552
6553                if (mRecyclerListener != null) {
6554                    mRecyclerListener.onMovedToScrapHeap(scrap);
6555                }
6556            }
6557        }
6558
6559        /**
6560         * Finish the removal of any views that skipped the scrap heap.
6561         */
6562        void removeSkippedScrap() {
6563            if (mSkippedScrap == null) {
6564                return;
6565            }
6566            final int count = mSkippedScrap.size();
6567            for (int i = 0; i < count; i++) {
6568                removeDetachedView(mSkippedScrap.get(i), false);
6569            }
6570            mSkippedScrap.clear();
6571        }
6572
6573        /**
6574         * Move all views remaining in mActiveViews to mScrapViews.
6575         */
6576        void scrapActiveViews() {
6577            final View[] activeViews = mActiveViews;
6578            final boolean hasListener = mRecyclerListener != null;
6579            final boolean multipleScraps = mViewTypeCount > 1;
6580
6581            ArrayList<View> scrapViews = mCurrentScrap;
6582            final int count = activeViews.length;
6583            for (int i = count - 1; i >= 0; i--) {
6584                final View victim = activeViews[i];
6585                if (victim != null) {
6586                    final AbsListView.LayoutParams lp
6587                            = (AbsListView.LayoutParams) victim.getLayoutParams();
6588                    final int whichScrap = lp.viewType;
6589
6590                    activeViews[i] = null;
6591
6592                    if (victim.hasTransientState()) {
6593                        // Store views with transient state for later use.
6594                        victim.dispatchStartTemporaryDetach();
6595
6596                        if (mAdapter != null && mAdapterHasStableIds) {
6597                            if (mTransientStateViewsById == null) {
6598                                mTransientStateViewsById = new LongSparseArray<View>();
6599                            }
6600                            long id = mAdapter.getItemId(mFirstActivePosition + i);
6601                            mTransientStateViewsById.put(id, victim);
6602                        } else if (!mDataChanged) {
6603                            if (mTransientStateViews == null) {
6604                                mTransientStateViews = new SparseArray<View>();
6605                            }
6606                            mTransientStateViews.put(mFirstActivePosition + i, victim);
6607                        } else if (whichScrap != ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
6608                            // The data has changed, we can't keep this view.
6609                            removeDetachedView(victim, false);
6610                        }
6611                    } else if (!shouldRecycleViewType(whichScrap)) {
6612                        // Discard non-recyclable views except headers/footers.
6613                        if (whichScrap != ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
6614                            removeDetachedView(victim, false);
6615                        }
6616                    } else {
6617                        // Store everything else on the appropriate scrap heap.
6618                        if (multipleScraps) {
6619                            scrapViews = mScrapViews[whichScrap];
6620                        }
6621
6622                        victim.dispatchStartTemporaryDetach();
6623                        lp.scrappedFromPosition = mFirstActivePosition + i;
6624                        scrapViews.add(victim);
6625
6626                        if (hasListener) {
6627                            mRecyclerListener.onMovedToScrapHeap(victim);
6628                        }
6629                    }
6630                }
6631            }
6632
6633            pruneScrapViews();
6634        }
6635
6636        /**
6637         * Makes sure that the size of mScrapViews does not exceed the size of
6638         * mActiveViews, which can happen if an adapter does not recycle its
6639         * views. Removes cached transient state views that no longer have
6640         * transient state.
6641         */
6642        private void pruneScrapViews() {
6643            final int maxViews = mActiveViews.length;
6644            final int viewTypeCount = mViewTypeCount;
6645            final ArrayList<View>[] scrapViews = mScrapViews;
6646            for (int i = 0; i < viewTypeCount; ++i) {
6647                final ArrayList<View> scrapPile = scrapViews[i];
6648                int size = scrapPile.size();
6649                final int extras = size - maxViews;
6650                size--;
6651                for (int j = 0; j < extras; j++) {
6652                    removeDetachedView(scrapPile.remove(size--), false);
6653                }
6654            }
6655
6656            final SparseArray<View> transViewsByPos = mTransientStateViews;
6657            if (transViewsByPos != null) {
6658                for (int i = 0; i < transViewsByPos.size(); i++) {
6659                    final View v = transViewsByPos.valueAt(i);
6660                    if (!v.hasTransientState()) {
6661                        removeDetachedView(v, false);
6662                        transViewsByPos.removeAt(i);
6663                        i--;
6664                    }
6665                }
6666            }
6667
6668            final LongSparseArray<View> transViewsById = mTransientStateViewsById;
6669            if (transViewsById != null) {
6670                for (int i = 0; i < transViewsById.size(); i++) {
6671                    final View v = transViewsById.valueAt(i);
6672                    if (!v.hasTransientState()) {
6673                        removeDetachedView(v, false);
6674                        transViewsById.removeAt(i);
6675                        i--;
6676                    }
6677                }
6678            }
6679        }
6680
6681        /**
6682         * Puts all views in the scrap heap into the supplied list.
6683         */
6684        void reclaimScrapViews(List<View> views) {
6685            if (mViewTypeCount == 1) {
6686                views.addAll(mCurrentScrap);
6687            } else {
6688                final int viewTypeCount = mViewTypeCount;
6689                final ArrayList<View>[] scrapViews = mScrapViews;
6690                for (int i = 0; i < viewTypeCount; ++i) {
6691                    final ArrayList<View> scrapPile = scrapViews[i];
6692                    views.addAll(scrapPile);
6693                }
6694            }
6695        }
6696
6697        /**
6698         * Updates the cache color hint of all known views.
6699         *
6700         * @param color The new cache color hint.
6701         */
6702        void setCacheColorHint(int color) {
6703            if (mViewTypeCount == 1) {
6704                final ArrayList<View> scrap = mCurrentScrap;
6705                final int scrapCount = scrap.size();
6706                for (int i = 0; i < scrapCount; i++) {
6707                    scrap.get(i).setDrawingCacheBackgroundColor(color);
6708                }
6709            } else {
6710                final int typeCount = mViewTypeCount;
6711                for (int i = 0; i < typeCount; i++) {
6712                    final ArrayList<View> scrap = mScrapViews[i];
6713                    final int scrapCount = scrap.size();
6714                    for (int j = 0; j < scrapCount; j++) {
6715                        scrap.get(j).setDrawingCacheBackgroundColor(color);
6716                    }
6717                }
6718            }
6719            // Just in case this is called during a layout pass
6720            final View[] activeViews = mActiveViews;
6721            final int count = activeViews.length;
6722            for (int i = 0; i < count; ++i) {
6723                final View victim = activeViews[i];
6724                if (victim != null) {
6725                    victim.setDrawingCacheBackgroundColor(color);
6726                }
6727            }
6728        }
6729
6730        private View retrieveFromScrap(ArrayList<View> scrapViews, int position) {
6731            final int size = scrapViews.size();
6732            if (size > 0) {
6733                // See if we still have a view for this position or ID.
6734                for (int i = 0; i < size; i++) {
6735                    final View view = scrapViews.get(i);
6736                    final AbsListView.LayoutParams params =
6737                            (AbsListView.LayoutParams) view.getLayoutParams();
6738
6739                    if (mAdapterHasStableIds) {
6740                        final long id = mAdapter.getItemId(position);
6741                        if (id == params.itemId) {
6742                            return scrapViews.remove(i);
6743                        }
6744                    } else if (params.scrappedFromPosition == position) {
6745                        final View scrap = scrapViews.remove(i);
6746                        clearAccessibilityFromScrap(scrap);
6747                        return scrap;
6748                    }
6749                }
6750                final View scrap = scrapViews.remove(size - 1);
6751                clearAccessibilityFromScrap(scrap);
6752                return scrap;
6753            } else {
6754                return null;
6755            }
6756        }
6757
6758        private void clearScrap(final ArrayList<View> scrap) {
6759            final int scrapCount = scrap.size();
6760            for (int j = 0; j < scrapCount; j++) {
6761                removeDetachedView(scrap.remove(scrapCount - 1 - j), false);
6762            }
6763        }
6764
6765        private void clearAccessibilityFromScrap(View view) {
6766            if (view.isAccessibilityFocused()) {
6767                view.clearAccessibilityFocus();
6768            }
6769            view.setAccessibilityDelegate(null);
6770        }
6771
6772        private void removeDetachedView(View child, boolean animate) {
6773            child.setAccessibilityDelegate(null);
6774            AbsListView.this.removeDetachedView(child, animate);
6775        }
6776    }
6777
6778    /**
6779     * Returns the height of the view for the specified position.
6780     *
6781     * @param position the item position
6782     * @return view height in pixels
6783     */
6784    int getHeightForPosition(int position) {
6785        final int firstVisiblePosition = getFirstVisiblePosition();
6786        final int childCount = getChildCount();
6787        final int index = position - firstVisiblePosition;
6788        if (index >= 0 && index < childCount) {
6789            // Position is on-screen, use existing view.
6790            final View view = getChildAt(index);
6791            return view.getHeight();
6792        } else {
6793            // Position is off-screen, obtain & recycle view.
6794            final View view = obtainView(position, mIsScrap);
6795            view.measure(mWidthMeasureSpec, MeasureSpec.UNSPECIFIED);
6796            final int height = view.getMeasuredHeight();
6797            mRecycler.addScrapView(view, position);
6798            return height;
6799        }
6800    }
6801
6802    /**
6803     * Sets the selected item and positions the selection y pixels from the top edge
6804     * of the ListView. (If in touch mode, the item will not be selected but it will
6805     * still be positioned appropriately.)
6806     *
6807     * @param position Index (starting at 0) of the data item to be selected.
6808     * @param y The distance from the top edge of the ListView (plus padding) that the
6809     *        item will be positioned.
6810     */
6811    public void setSelectionFromTop(int position, int y) {
6812        if (mAdapter == null) {
6813            return;
6814        }
6815
6816        if (!isInTouchMode()) {
6817            position = lookForSelectablePosition(position, true);
6818            if (position >= 0) {
6819                setNextSelectedPositionInt(position);
6820            }
6821        } else {
6822            mResurrectToPosition = position;
6823        }
6824
6825        if (position >= 0) {
6826            mLayoutMode = LAYOUT_SPECIFIC;
6827            mSpecificTop = mListPadding.top + y;
6828
6829            if (mNeedSync) {
6830                mSyncPosition = position;
6831                mSyncRowId = mAdapter.getItemId(position);
6832            }
6833
6834            if (mPositionScroller != null) {
6835                mPositionScroller.stop();
6836            }
6837            requestLayout();
6838        }
6839    }
6840
6841    /**
6842     * Abstract positon scroller used to handle smooth scrolling.
6843     */
6844    static abstract class AbsPositionScroller {
6845        public abstract void start(int position);
6846        public abstract void start(int position, int boundPosition);
6847        public abstract void startWithOffset(int position, int offset);
6848        public abstract void startWithOffset(int position, int offset, int duration);
6849        public abstract void stop();
6850    }
6851
6852    /**
6853     * Default position scroller that simulates a fling.
6854     */
6855    class PositionScroller extends AbsPositionScroller implements Runnable {
6856        private static final int SCROLL_DURATION = 200;
6857
6858        private static final int MOVE_DOWN_POS = 1;
6859        private static final int MOVE_UP_POS = 2;
6860        private static final int MOVE_DOWN_BOUND = 3;
6861        private static final int MOVE_UP_BOUND = 4;
6862        private static final int MOVE_OFFSET = 5;
6863
6864        private int mMode;
6865        private int mTargetPos;
6866        private int mBoundPos;
6867        private int mLastSeenPos;
6868        private int mScrollDuration;
6869        private final int mExtraScroll;
6870
6871        private int mOffsetFromTop;
6872
6873        PositionScroller() {
6874            mExtraScroll = ViewConfiguration.get(mContext).getScaledFadingEdgeLength();
6875        }
6876
6877        @Override
6878        public void start(final int position) {
6879            stop();
6880
6881            if (mDataChanged) {
6882                // Wait until we're back in a stable state to try this.
6883                mPositionScrollAfterLayout = new Runnable() {
6884                    @Override public void run() {
6885                        start(position);
6886                    }
6887                };
6888                return;
6889            }
6890
6891            final int childCount = getChildCount();
6892            if (childCount == 0) {
6893                // Can't scroll without children.
6894                return;
6895            }
6896
6897            final int firstPos = mFirstPosition;
6898            final int lastPos = firstPos + childCount - 1;
6899
6900            int viewTravelCount;
6901            int clampedPosition = Math.max(0, Math.min(getCount() - 1, position));
6902            if (clampedPosition < firstPos) {
6903                viewTravelCount = firstPos - clampedPosition + 1;
6904                mMode = MOVE_UP_POS;
6905            } else if (clampedPosition > lastPos) {
6906                viewTravelCount = clampedPosition - lastPos + 1;
6907                mMode = MOVE_DOWN_POS;
6908            } else {
6909                scrollToVisible(clampedPosition, INVALID_POSITION, SCROLL_DURATION);
6910                return;
6911            }
6912
6913            if (viewTravelCount > 0) {
6914                mScrollDuration = SCROLL_DURATION / viewTravelCount;
6915            } else {
6916                mScrollDuration = SCROLL_DURATION;
6917            }
6918            mTargetPos = clampedPosition;
6919            mBoundPos = INVALID_POSITION;
6920            mLastSeenPos = INVALID_POSITION;
6921
6922            postOnAnimation(this);
6923        }
6924
6925        @Override
6926        public void start(final int position, final int boundPosition) {
6927            stop();
6928
6929            if (boundPosition == INVALID_POSITION) {
6930                start(position);
6931                return;
6932            }
6933
6934            if (mDataChanged) {
6935                // Wait until we're back in a stable state to try this.
6936                mPositionScrollAfterLayout = new Runnable() {
6937                    @Override public void run() {
6938                        start(position, boundPosition);
6939                    }
6940                };
6941                return;
6942            }
6943
6944            final int childCount = getChildCount();
6945            if (childCount == 0) {
6946                // Can't scroll without children.
6947                return;
6948            }
6949
6950            final int firstPos = mFirstPosition;
6951            final int lastPos = firstPos + childCount - 1;
6952
6953            int viewTravelCount;
6954            int clampedPosition = Math.max(0, Math.min(getCount() - 1, position));
6955            if (clampedPosition < firstPos) {
6956                final int boundPosFromLast = lastPos - boundPosition;
6957                if (boundPosFromLast < 1) {
6958                    // Moving would shift our bound position off the screen. Abort.
6959                    return;
6960                }
6961
6962                final int posTravel = firstPos - clampedPosition + 1;
6963                final int boundTravel = boundPosFromLast - 1;
6964                if (boundTravel < posTravel) {
6965                    viewTravelCount = boundTravel;
6966                    mMode = MOVE_UP_BOUND;
6967                } else {
6968                    viewTravelCount = posTravel;
6969                    mMode = MOVE_UP_POS;
6970                }
6971            } else if (clampedPosition > lastPos) {
6972                final int boundPosFromFirst = boundPosition - firstPos;
6973                if (boundPosFromFirst < 1) {
6974                    // Moving would shift our bound position off the screen. Abort.
6975                    return;
6976                }
6977
6978                final int posTravel = clampedPosition - lastPos + 1;
6979                final int boundTravel = boundPosFromFirst - 1;
6980                if (boundTravel < posTravel) {
6981                    viewTravelCount = boundTravel;
6982                    mMode = MOVE_DOWN_BOUND;
6983                } else {
6984                    viewTravelCount = posTravel;
6985                    mMode = MOVE_DOWN_POS;
6986                }
6987            } else {
6988                scrollToVisible(clampedPosition, boundPosition, SCROLL_DURATION);
6989                return;
6990            }
6991
6992            if (viewTravelCount > 0) {
6993                mScrollDuration = SCROLL_DURATION / viewTravelCount;
6994            } else {
6995                mScrollDuration = SCROLL_DURATION;
6996            }
6997            mTargetPos = clampedPosition;
6998            mBoundPos = boundPosition;
6999            mLastSeenPos = INVALID_POSITION;
7000
7001            postOnAnimation(this);
7002        }
7003
7004        @Override
7005        public void startWithOffset(int position, int offset) {
7006            startWithOffset(position, offset, SCROLL_DURATION);
7007        }
7008
7009        @Override
7010        public void startWithOffset(final int position, int offset, final int duration) {
7011            stop();
7012
7013            if (mDataChanged) {
7014                // Wait until we're back in a stable state to try this.
7015                final int postOffset = offset;
7016                mPositionScrollAfterLayout = new Runnable() {
7017                    @Override public void run() {
7018                        startWithOffset(position, postOffset, duration);
7019                    }
7020                };
7021                return;
7022            }
7023
7024            final int childCount = getChildCount();
7025            if (childCount == 0) {
7026                // Can't scroll without children.
7027                return;
7028            }
7029
7030            offset += getPaddingTop();
7031
7032            mTargetPos = Math.max(0, Math.min(getCount() - 1, position));
7033            mOffsetFromTop = offset;
7034            mBoundPos = INVALID_POSITION;
7035            mLastSeenPos = INVALID_POSITION;
7036            mMode = MOVE_OFFSET;
7037
7038            final int firstPos = mFirstPosition;
7039            final int lastPos = firstPos + childCount - 1;
7040
7041            int viewTravelCount;
7042            if (mTargetPos < firstPos) {
7043                viewTravelCount = firstPos - mTargetPos;
7044            } else if (mTargetPos > lastPos) {
7045                viewTravelCount = mTargetPos - lastPos;
7046            } else {
7047                // On-screen, just scroll.
7048                final int targetTop = getChildAt(mTargetPos - firstPos).getTop();
7049                smoothScrollBy(targetTop - offset, duration, true);
7050                return;
7051            }
7052
7053            // Estimate how many screens we should travel
7054            final float screenTravelCount = (float) viewTravelCount / childCount;
7055            mScrollDuration = screenTravelCount < 1 ?
7056                    duration : (int) (duration / screenTravelCount);
7057            mLastSeenPos = INVALID_POSITION;
7058
7059            postOnAnimation(this);
7060        }
7061
7062        /**
7063         * Scroll such that targetPos is in the visible padded region without scrolling
7064         * boundPos out of view. Assumes targetPos is onscreen.
7065         */
7066        private void scrollToVisible(int targetPos, int boundPos, int duration) {
7067            final int firstPos = mFirstPosition;
7068            final int childCount = getChildCount();
7069            final int lastPos = firstPos + childCount - 1;
7070            final int paddedTop = mListPadding.top;
7071            final int paddedBottom = getHeight() - mListPadding.bottom;
7072
7073            if (targetPos < firstPos || targetPos > lastPos) {
7074                Log.w(TAG, "scrollToVisible called with targetPos " + targetPos +
7075                        " not visible [" + firstPos + ", " + lastPos + "]");
7076            }
7077            if (boundPos < firstPos || boundPos > lastPos) {
7078                // boundPos doesn't matter, it's already offscreen.
7079                boundPos = INVALID_POSITION;
7080            }
7081
7082            final View targetChild = getChildAt(targetPos - firstPos);
7083            final int targetTop = targetChild.getTop();
7084            final int targetBottom = targetChild.getBottom();
7085            int scrollBy = 0;
7086
7087            if (targetBottom > paddedBottom) {
7088                scrollBy = targetBottom - paddedBottom;
7089            }
7090            if (targetTop < paddedTop) {
7091                scrollBy = targetTop - paddedTop;
7092            }
7093
7094            if (scrollBy == 0) {
7095                return;
7096            }
7097
7098            if (boundPos >= 0) {
7099                final View boundChild = getChildAt(boundPos - firstPos);
7100                final int boundTop = boundChild.getTop();
7101                final int boundBottom = boundChild.getBottom();
7102                final int absScroll = Math.abs(scrollBy);
7103
7104                if (scrollBy < 0 && boundBottom + absScroll > paddedBottom) {
7105                    // Don't scroll the bound view off the bottom of the screen.
7106                    scrollBy = Math.max(0, boundBottom - paddedBottom);
7107                } else if (scrollBy > 0 && boundTop - absScroll < paddedTop) {
7108                    // Don't scroll the bound view off the top of the screen.
7109                    scrollBy = Math.min(0, boundTop - paddedTop);
7110                }
7111            }
7112
7113            smoothScrollBy(scrollBy, duration);
7114        }
7115
7116        @Override
7117        public void stop() {
7118            removeCallbacks(this);
7119        }
7120
7121        @Override
7122        public void run() {
7123            final int listHeight = getHeight();
7124            final int firstPos = mFirstPosition;
7125
7126            switch (mMode) {
7127            case MOVE_DOWN_POS: {
7128                final int lastViewIndex = getChildCount() - 1;
7129                final int lastPos = firstPos + lastViewIndex;
7130
7131                if (lastViewIndex < 0) {
7132                    return;
7133                }
7134
7135                if (lastPos == mLastSeenPos) {
7136                    // No new views, let things keep going.
7137                    postOnAnimation(this);
7138                    return;
7139                }
7140
7141                final View lastView = getChildAt(lastViewIndex);
7142                final int lastViewHeight = lastView.getHeight();
7143                final int lastViewTop = lastView.getTop();
7144                final int lastViewPixelsShowing = listHeight - lastViewTop;
7145                final int extraScroll = lastPos < mItemCount - 1 ?
7146                        Math.max(mListPadding.bottom, mExtraScroll) : mListPadding.bottom;
7147
7148                final int scrollBy = lastViewHeight - lastViewPixelsShowing + extraScroll;
7149                smoothScrollBy(scrollBy, mScrollDuration, true);
7150
7151                mLastSeenPos = lastPos;
7152                if (lastPos < mTargetPos) {
7153                    postOnAnimation(this);
7154                }
7155                break;
7156            }
7157
7158            case MOVE_DOWN_BOUND: {
7159                final int nextViewIndex = 1;
7160                final int childCount = getChildCount();
7161
7162                if (firstPos == mBoundPos || childCount <= nextViewIndex
7163                        || firstPos + childCount >= mItemCount) {
7164                    return;
7165                }
7166                final int nextPos = firstPos + nextViewIndex;
7167
7168                if (nextPos == mLastSeenPos) {
7169                    // No new views, let things keep going.
7170                    postOnAnimation(this);
7171                    return;
7172                }
7173
7174                final View nextView = getChildAt(nextViewIndex);
7175                final int nextViewHeight = nextView.getHeight();
7176                final int nextViewTop = nextView.getTop();
7177                final int extraScroll = Math.max(mListPadding.bottom, mExtraScroll);
7178                if (nextPos < mBoundPos) {
7179                    smoothScrollBy(Math.max(0, nextViewHeight + nextViewTop - extraScroll),
7180                            mScrollDuration, true);
7181
7182                    mLastSeenPos = nextPos;
7183
7184                    postOnAnimation(this);
7185                } else  {
7186                    if (nextViewTop > extraScroll) {
7187                        smoothScrollBy(nextViewTop - extraScroll, mScrollDuration, true);
7188                    }
7189                }
7190                break;
7191            }
7192
7193            case MOVE_UP_POS: {
7194                if (firstPos == mLastSeenPos) {
7195                    // No new views, let things keep going.
7196                    postOnAnimation(this);
7197                    return;
7198                }
7199
7200                final View firstView = getChildAt(0);
7201                if (firstView == null) {
7202                    return;
7203                }
7204                final int firstViewTop = firstView.getTop();
7205                final int extraScroll = firstPos > 0 ?
7206                        Math.max(mExtraScroll, mListPadding.top) : mListPadding.top;
7207
7208                smoothScrollBy(firstViewTop - extraScroll, mScrollDuration, true);
7209
7210                mLastSeenPos = firstPos;
7211
7212                if (firstPos > mTargetPos) {
7213                    postOnAnimation(this);
7214                }
7215                break;
7216            }
7217
7218            case MOVE_UP_BOUND: {
7219                final int lastViewIndex = getChildCount() - 2;
7220                if (lastViewIndex < 0) {
7221                    return;
7222                }
7223                final int lastPos = firstPos + lastViewIndex;
7224
7225                if (lastPos == mLastSeenPos) {
7226                    // No new views, let things keep going.
7227                    postOnAnimation(this);
7228                    return;
7229                }
7230
7231                final View lastView = getChildAt(lastViewIndex);
7232                final int lastViewHeight = lastView.getHeight();
7233                final int lastViewTop = lastView.getTop();
7234                final int lastViewPixelsShowing = listHeight - lastViewTop;
7235                final int extraScroll = Math.max(mListPadding.top, mExtraScroll);
7236                mLastSeenPos = lastPos;
7237                if (lastPos > mBoundPos) {
7238                    smoothScrollBy(-(lastViewPixelsShowing - extraScroll), mScrollDuration, true);
7239                    postOnAnimation(this);
7240                } else {
7241                    final int bottom = listHeight - extraScroll;
7242                    final int lastViewBottom = lastViewTop + lastViewHeight;
7243                    if (bottom > lastViewBottom) {
7244                        smoothScrollBy(-(bottom - lastViewBottom), mScrollDuration, true);
7245                    }
7246                }
7247                break;
7248            }
7249
7250            case MOVE_OFFSET: {
7251                if (mLastSeenPos == firstPos) {
7252                    // No new views, let things keep going.
7253                    postOnAnimation(this);
7254                    return;
7255                }
7256
7257                mLastSeenPos = firstPos;
7258
7259                final int childCount = getChildCount();
7260                final int position = mTargetPos;
7261                final int lastPos = firstPos + childCount - 1;
7262
7263                int viewTravelCount = 0;
7264                if (position < firstPos) {
7265                    viewTravelCount = firstPos - position + 1;
7266                } else if (position > lastPos) {
7267                    viewTravelCount = position - lastPos;
7268                }
7269
7270                // Estimate how many screens we should travel
7271                final float screenTravelCount = (float) viewTravelCount / childCount;
7272
7273                final float modifier = Math.min(Math.abs(screenTravelCount), 1.f);
7274                if (position < firstPos) {
7275                    final int distance = (int) (-getHeight() * modifier);
7276                    final int duration = (int) (mScrollDuration * modifier);
7277                    smoothScrollBy(distance, duration, true);
7278                    postOnAnimation(this);
7279                } else if (position > lastPos) {
7280                    final int distance = (int) (getHeight() * modifier);
7281                    final int duration = (int) (mScrollDuration * modifier);
7282                    smoothScrollBy(distance, duration, true);
7283                    postOnAnimation(this);
7284                } else {
7285                    // On-screen, just scroll.
7286                    final int targetTop = getChildAt(position - firstPos).getTop();
7287                    final int distance = targetTop - mOffsetFromTop;
7288                    final int duration = (int) (mScrollDuration *
7289                            ((float) Math.abs(distance) / getHeight()));
7290                    smoothScrollBy(distance, duration, true);
7291                }
7292                break;
7293            }
7294
7295            default:
7296                break;
7297            }
7298        }
7299    }
7300}
7301