ListView.java revision 385a655b8e8bf85024e4f24f1d7f6c2d7d7e900d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.widget;
18
19import com.android.internal.R;
20import com.google.android.collect.Lists;
21
22import android.content.Context;
23import android.content.Intent;
24import android.content.res.TypedArray;
25import android.graphics.Canvas;
26import android.graphics.Paint;
27import android.graphics.PixelFormat;
28import android.graphics.Rect;
29import android.graphics.drawable.ColorDrawable;
30import android.graphics.drawable.Drawable;
31import android.util.AttributeSet;
32import android.util.SparseBooleanArray;
33import android.view.FocusFinder;
34import android.view.KeyEvent;
35import android.view.MotionEvent;
36import android.view.SoundEffectConstants;
37import android.view.View;
38import android.view.ViewDebug;
39import android.view.ViewGroup;
40import android.view.ViewParent;
41import android.view.accessibility.AccessibilityEvent;
42import android.widget.RemoteViews.RemoteView;
43
44import java.util.ArrayList;
45
46/*
47 * Implementation Notes:
48 *
49 * Some terminology:
50 *
51 *     index    - index of the items that are currently visible
52 *     position - index of the items in the cursor
53 */
54
55
56/**
57 * A view that shows items in a vertically scrolling list. The items
58 * come from the {@link ListAdapter} associated with this view.
59 *
60 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-listview.html">List View
61 * tutorial</a>.</p>
62 *
63 * @attr ref android.R.styleable#ListView_entries
64 * @attr ref android.R.styleable#ListView_divider
65 * @attr ref android.R.styleable#ListView_dividerHeight
66 * @attr ref android.R.styleable#ListView_headerDividersEnabled
67 * @attr ref android.R.styleable#ListView_footerDividersEnabled
68 */
69@RemoteView
70public class ListView extends AbsListView {
71    /**
72     * Used to indicate a no preference for a position type.
73     */
74    static final int NO_POSITION = -1;
75
76    /**
77     * When arrow scrolling, ListView will never scroll more than this factor
78     * times the height of the list.
79     */
80    private static final float MAX_SCROLL_FACTOR = 0.33f;
81
82    /**
83     * When arrow scrolling, need a certain amount of pixels to preview next
84     * items.  This is usually the fading edge, but if that is small enough,
85     * we want to make sure we preview at least this many pixels.
86     */
87    private static final int MIN_SCROLL_PREVIEW_PIXELS = 2;
88
89    /**
90     * A class that represents a fixed view in a list, for example a header at the top
91     * or a footer at the bottom.
92     */
93    public class FixedViewInfo {
94        /** The view to add to the list */
95        public View view;
96        /** The data backing the view. This is returned from {@link ListAdapter#getItem(int)}. */
97        public Object data;
98        /** <code>true</code> if the fixed view should be selectable in the list */
99        public boolean isSelectable;
100    }
101
102    private ArrayList<FixedViewInfo> mHeaderViewInfos = Lists.newArrayList();
103    private ArrayList<FixedViewInfo> mFooterViewInfos = Lists.newArrayList();
104
105    Drawable mDivider;
106    int mDividerHeight;
107
108    private boolean mIsCacheColorOpaque;
109    private boolean mDividerIsOpaque;
110    private boolean mClipDivider;
111
112    private boolean mHeaderDividersEnabled;
113    private boolean mFooterDividersEnabled;
114
115    private boolean mAreAllItemsSelectable = true;
116
117    private boolean mItemsCanFocus = false;
118
119    // used for temporary calculations.
120    private final Rect mTempRect = new Rect();
121    private Paint mDividerPaint;
122
123    // the single allocated result per list view; kinda cheesey but avoids
124    // allocating these thingies too often.
125    private final ArrowScrollFocusResult mArrowScrollFocusResult = new ArrowScrollFocusResult();
126
127    // Keeps focused children visible through resizes
128    private FocusSelector mFocusSelector;
129
130    public ListView(Context context) {
131        this(context, null);
132    }
133
134    public ListView(Context context, AttributeSet attrs) {
135        this(context, attrs, com.android.internal.R.attr.listViewStyle);
136    }
137
138    public ListView(Context context, AttributeSet attrs, int defStyle) {
139        super(context, attrs, defStyle);
140
141        TypedArray a = context.obtainStyledAttributes(attrs,
142                com.android.internal.R.styleable.ListView, defStyle, 0);
143
144        CharSequence[] entries = a.getTextArray(
145                com.android.internal.R.styleable.ListView_entries);
146        if (entries != null) {
147            setAdapter(new ArrayAdapter<CharSequence>(context,
148                    com.android.internal.R.layout.simple_list_item_1, entries));
149        }
150
151        final Drawable d = a.getDrawable(com.android.internal.R.styleable.ListView_divider);
152        if (d != null) {
153            // If a divider is specified use its intrinsic height for divider height
154            setDivider(d);
155        }
156
157        // Use the height specified, zero being the default
158        final int dividerHeight = a.getDimensionPixelSize(
159                com.android.internal.R.styleable.ListView_dividerHeight, 0);
160        if (dividerHeight != 0) {
161            setDividerHeight(dividerHeight);
162        }
163
164        mHeaderDividersEnabled = a.getBoolean(R.styleable.ListView_headerDividersEnabled, true);
165        mFooterDividersEnabled = a.getBoolean(R.styleable.ListView_footerDividersEnabled, true);
166
167        a.recycle();
168    }
169
170    /**
171     * @return The maximum amount a list view will scroll in response to
172     *   an arrow event.
173     */
174    public int getMaxScrollAmount() {
175        return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop));
176    }
177
178    /**
179     * Make sure views are touching the top or bottom edge, as appropriate for
180     * our gravity
181     */
182    private void adjustViewsUpOrDown() {
183        final int childCount = getChildCount();
184        int delta;
185
186        if (childCount > 0) {
187            View child;
188
189            if (!mStackFromBottom) {
190                // Uh-oh -- we came up short. Slide all views up to make them
191                // align with the top
192                child = getChildAt(0);
193                delta = child.getTop() - mListPadding.top;
194                if (mFirstPosition != 0) {
195                    // It's OK to have some space above the first item if it is
196                    // part of the vertical spacing
197                    delta -= mDividerHeight;
198                }
199                if (delta < 0) {
200                    // We only are looking to see if we are too low, not too high
201                    delta = 0;
202                }
203            } else {
204                // we are too high, slide all views down to align with bottom
205                child = getChildAt(childCount - 1);
206                delta = child.getBottom() - (getHeight() - mListPadding.bottom);
207
208                if (mFirstPosition + childCount < mItemCount) {
209                    // It's OK to have some space below the last item if it is
210                    // part of the vertical spacing
211                    delta += mDividerHeight;
212                }
213
214                if (delta > 0) {
215                    delta = 0;
216                }
217            }
218
219            if (delta != 0) {
220                offsetChildrenTopAndBottom(-delta);
221            }
222        }
223    }
224
225    /**
226     * Add a fixed view to appear at the top of the list. If addHeaderView is
227     * called more than once, the views will appear in the order they were
228     * added. Views added using this call can take focus if they want.
229     * <p>
230     * NOTE: Call this before calling setAdapter. This is so ListView can wrap
231     * the supplied cursor with one that will also account for header and footer
232     * views.
233     *
234     * @param v The view to add.
235     * @param data Data to associate with this view
236     * @param isSelectable whether the item is selectable
237     */
238    public void addHeaderView(View v, Object data, boolean isSelectable) {
239
240        if (mAdapter != null) {
241            throw new IllegalStateException(
242                    "Cannot add header view to list -- setAdapter has already been called.");
243        }
244
245        FixedViewInfo info = new FixedViewInfo();
246        info.view = v;
247        info.data = data;
248        info.isSelectable = isSelectable;
249        mHeaderViewInfos.add(info);
250    }
251
252    /**
253     * Add a fixed view to appear at the top of the list. If addHeaderView is
254     * called more than once, the views will appear in the order they were
255     * added. Views added using this call can take focus if they want.
256     * <p>
257     * NOTE: Call this before calling setAdapter. This is so ListView can wrap
258     * the supplied cursor with one that will also account for header and footer
259     * views.
260     *
261     * @param v The view to add.
262     */
263    public void addHeaderView(View v) {
264        addHeaderView(v, null, true);
265    }
266
267    @Override
268    public int getHeaderViewsCount() {
269        return mHeaderViewInfos.size();
270    }
271
272    /**
273     * Removes a previously-added header view.
274     *
275     * @param v The view to remove
276     * @return true if the view was removed, false if the view was not a header
277     *         view
278     */
279    public boolean removeHeaderView(View v) {
280        if (mHeaderViewInfos.size() > 0) {
281            boolean result = false;
282            if (((HeaderViewListAdapter) mAdapter).removeHeader(v)) {
283                mDataSetObserver.onChanged();
284                result = true;
285            }
286            removeFixedViewInfo(v, mHeaderViewInfos);
287            return result;
288        }
289        return false;
290    }
291
292    private void removeFixedViewInfo(View v, ArrayList<FixedViewInfo> where) {
293        int len = where.size();
294        for (int i = 0; i < len; ++i) {
295            FixedViewInfo info = where.get(i);
296            if (info.view == v) {
297                where.remove(i);
298                break;
299            }
300        }
301    }
302
303    /**
304     * Add a fixed view to appear at the bottom of the list. If addFooterView is
305     * called more than once, the views will appear in the order they were
306     * added. Views added using this call can take focus if they want.
307     * <p>
308     * NOTE: Call this before calling setAdapter. This is so ListView can wrap
309     * the supplied cursor with one that will also account for header and footer
310     * views.
311     *
312     * @param v The view to add.
313     * @param data Data to associate with this view
314     * @param isSelectable true if the footer view can be selected
315     */
316    public void addFooterView(View v, Object data, boolean isSelectable) {
317        FixedViewInfo info = new FixedViewInfo();
318        info.view = v;
319        info.data = data;
320        info.isSelectable = isSelectable;
321        mFooterViewInfos.add(info);
322
323        // in the case of re-adding a footer view, or adding one later on,
324        // we need to notify the observer
325        if (mDataSetObserver != null) {
326            mDataSetObserver.onChanged();
327        }
328    }
329
330    /**
331     * Add a fixed view to appear at the bottom of the list. If addFooterView is called more
332     * than once, the views will appear in the order they were added. Views added using
333     * this call can take focus if they want.
334     * <p>NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied
335     * cursor with one that will also account for header and footer views.
336     *
337     *
338     * @param v The view to add.
339     */
340    public void addFooterView(View v) {
341        addFooterView(v, null, true);
342    }
343
344    @Override
345    public int getFooterViewsCount() {
346        return mFooterViewInfos.size();
347    }
348
349    /**
350     * Removes a previously-added footer view.
351     *
352     * @param v The view to remove
353     * @return
354     * true if the view was removed, false if the view was not a footer view
355     */
356    public boolean removeFooterView(View v) {
357        if (mFooterViewInfos.size() > 0) {
358            boolean result = false;
359            if (((HeaderViewListAdapter) mAdapter).removeFooter(v)) {
360                mDataSetObserver.onChanged();
361                result = true;
362            }
363            removeFixedViewInfo(v, mFooterViewInfos);
364            return result;
365        }
366        return false;
367    }
368
369    /**
370     * Returns the adapter currently in use in this ListView. The returned adapter
371     * might not be the same adapter passed to {@link #setAdapter(ListAdapter)} but
372     * might be a {@link WrapperListAdapter}.
373     *
374     * @return The adapter currently used to display data in this ListView.
375     *
376     * @see #setAdapter(ListAdapter)
377     */
378    @Override
379    public ListAdapter getAdapter() {
380        return mAdapter;
381    }
382
383    /**
384     * Sets up this AbsListView to use a remote views adapter which connects to a RemoteViewsService
385     * through the specified intent.
386     * @param intent the intent used to identify the RemoteViewsService for the adapter to connect to.
387     */
388    @android.view.RemotableViewMethod
389    public void setRemoteViewsAdapter(Intent intent) {
390        super.setRemoteViewsAdapter(intent);
391    }
392
393    /**
394     * Sets the data behind this ListView.
395     *
396     * The adapter passed to this method may be wrapped by a {@link WrapperListAdapter},
397     * depending on the ListView features currently in use. For instance, adding
398     * headers and/or footers will cause the adapter to be wrapped.
399     *
400     * @param adapter The ListAdapter which is responsible for maintaining the
401     *        data backing this list and for producing a view to represent an
402     *        item in that data set.
403     *
404     * @see #getAdapter()
405     */
406    @Override
407    public void setAdapter(ListAdapter adapter) {
408        if (mAdapter != null && mDataSetObserver != null) {
409            mAdapter.unregisterDataSetObserver(mDataSetObserver);
410        }
411
412        resetList();
413        mRecycler.clear();
414
415        if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
416            mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
417        } else {
418            mAdapter = adapter;
419        }
420
421        mOldSelectedPosition = INVALID_POSITION;
422        mOldSelectedRowId = INVALID_ROW_ID;
423
424        // AbsListView#setAdapter will update choice mode states.
425        super.setAdapter(adapter);
426
427        if (mAdapter != null) {
428            mAreAllItemsSelectable = mAdapter.areAllItemsEnabled();
429            mOldItemCount = mItemCount;
430            mItemCount = mAdapter.getCount();
431            checkFocus();
432
433            mDataSetObserver = new AdapterDataSetObserver();
434            mAdapter.registerDataSetObserver(mDataSetObserver);
435
436            mRecycler.setViewTypeCount(mAdapter.getViewTypeCount());
437
438            int position;
439            if (mStackFromBottom) {
440                position = lookForSelectablePosition(mItemCount - 1, false);
441            } else {
442                position = lookForSelectablePosition(0, true);
443            }
444            setSelectedPositionInt(position);
445            setNextSelectedPositionInt(position);
446
447            if (mItemCount == 0) {
448                // Nothing selected
449                checkSelectionChanged();
450            }
451        } else {
452            mAreAllItemsSelectable = true;
453            checkFocus();
454            // Nothing selected
455            checkSelectionChanged();
456        }
457
458        requestLayout();
459    }
460
461
462    /**
463     * The list is empty. Clear everything out.
464     */
465    @Override
466    void resetList() {
467        // The parent's resetList() will remove all views from the layout so we need to
468        // cleanup the state of our footers and headers
469        clearRecycledState(mHeaderViewInfos);
470        clearRecycledState(mFooterViewInfos);
471
472        super.resetList();
473
474        mLayoutMode = LAYOUT_NORMAL;
475    }
476
477    private void clearRecycledState(ArrayList<FixedViewInfo> infos) {
478        if (infos != null) {
479            final int count = infos.size();
480
481            for (int i = 0; i < count; i++) {
482                final View child = infos.get(i).view;
483                final LayoutParams p = (LayoutParams) child.getLayoutParams();
484                if (p != null) {
485                    p.recycledHeaderFooter = false;
486                }
487            }
488        }
489    }
490
491    /**
492     * @return Whether the list needs to show the top fading edge
493     */
494    private boolean showingTopFadingEdge() {
495        final int listTop = mScrollY + mListPadding.top;
496        return (mFirstPosition > 0) || (getChildAt(0).getTop() > listTop);
497    }
498
499    /**
500     * @return Whether the list needs to show the bottom fading edge
501     */
502    private boolean showingBottomFadingEdge() {
503        final int childCount = getChildCount();
504        final int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
505        final int lastVisiblePosition = mFirstPosition + childCount - 1;
506
507        final int listBottom = mScrollY + getHeight() - mListPadding.bottom;
508
509        return (lastVisiblePosition < mItemCount - 1)
510                         || (bottomOfBottomChild < listBottom);
511    }
512
513
514    @Override
515    public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
516
517        int rectTopWithinChild = rect.top;
518
519        // offset so rect is in coordinates of the this view
520        rect.offset(child.getLeft(), child.getTop());
521        rect.offset(-child.getScrollX(), -child.getScrollY());
522
523        final int height = getHeight();
524        int listUnfadedTop = getScrollY();
525        int listUnfadedBottom = listUnfadedTop + height;
526        final int fadingEdge = getVerticalFadingEdgeLength();
527
528        if (showingTopFadingEdge()) {
529            // leave room for top fading edge as long as rect isn't at very top
530            if ((mSelectedPosition > 0) || (rectTopWithinChild > fadingEdge)) {
531                listUnfadedTop += fadingEdge;
532            }
533        }
534
535        int childCount = getChildCount();
536        int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
537
538        if (showingBottomFadingEdge()) {
539            // leave room for bottom fading edge as long as rect isn't at very bottom
540            if ((mSelectedPosition < mItemCount - 1)
541                    || (rect.bottom < (bottomOfBottomChild - fadingEdge))) {
542                listUnfadedBottom -= fadingEdge;
543            }
544        }
545
546        int scrollYDelta = 0;
547
548        if (rect.bottom > listUnfadedBottom && rect.top > listUnfadedTop) {
549            // need to MOVE DOWN to get it in view: move down just enough so
550            // that the entire rectangle is in view (or at least the first
551            // screen size chunk).
552
553            if (rect.height() > height) {
554                // just enough to get screen size chunk on
555                scrollYDelta += (rect.top - listUnfadedTop);
556            } else {
557                // get entire rect at bottom of screen
558                scrollYDelta += (rect.bottom - listUnfadedBottom);
559            }
560
561            // make sure we aren't scrolling beyond the end of our children
562            int distanceToBottom = bottomOfBottomChild - listUnfadedBottom;
563            scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
564        } else if (rect.top < listUnfadedTop && rect.bottom < listUnfadedBottom) {
565            // need to MOVE UP to get it in view: move up just enough so that
566            // entire rectangle is in view (or at least the first screen
567            // size chunk of it).
568
569            if (rect.height() > height) {
570                // screen size chunk
571                scrollYDelta -= (listUnfadedBottom - rect.bottom);
572            } else {
573                // entire rect at top
574                scrollYDelta -= (listUnfadedTop - rect.top);
575            }
576
577            // make sure we aren't scrolling any further than the top our children
578            int top = getChildAt(0).getTop();
579            int deltaToTop = top - listUnfadedTop;
580            scrollYDelta = Math.max(scrollYDelta, deltaToTop);
581        }
582
583        final boolean scroll = scrollYDelta != 0;
584        if (scroll) {
585            scrollListItemsBy(-scrollYDelta);
586            positionSelector(child);
587            mSelectedTop = child.getTop();
588            invalidate();
589        }
590        return scroll;
591    }
592
593    /**
594     * {@inheritDoc}
595     */
596    @Override
597    void fillGap(boolean down) {
598        final int count = getChildCount();
599        if (down) {
600            final int startOffset = count > 0 ? getChildAt(count - 1).getBottom() + mDividerHeight :
601                    getListPaddingTop();
602            fillDown(mFirstPosition + count, startOffset);
603            correctTooHigh(getChildCount());
604        } else {
605            final int startOffset = count > 0 ? getChildAt(0).getTop() - mDividerHeight :
606                    getHeight() - getListPaddingBottom();
607            fillUp(mFirstPosition - 1, startOffset);
608            correctTooLow(getChildCount());
609        }
610    }
611
612    /**
613     * Fills the list from pos down to the end of the list view.
614     *
615     * @param pos The first position to put in the list
616     *
617     * @param nextTop The location where the top of the item associated with pos
618     *        should be drawn
619     *
620     * @return The view that is currently selected, if it happens to be in the
621     *         range that we draw.
622     */
623    private View fillDown(int pos, int nextTop) {
624        View selectedView = null;
625
626        int end = (mBottom - mTop) - mListPadding.bottom;
627
628        while (nextTop < end && pos < mItemCount) {
629            // is this the selected item?
630            boolean selected = pos == mSelectedPosition;
631            View child = makeAndAddView(pos, nextTop, true, mListPadding.left, selected);
632
633            nextTop = child.getBottom() + mDividerHeight;
634            if (selected) {
635                selectedView = child;
636            }
637            pos++;
638        }
639
640        return selectedView;
641    }
642
643    /**
644     * Fills the list from pos up to the top of the list view.
645     *
646     * @param pos The first position to put in the list
647     *
648     * @param nextBottom The location where the bottom of the item associated
649     *        with pos should be drawn
650     *
651     * @return The view that is currently selected
652     */
653    private View fillUp(int pos, int nextBottom) {
654        View selectedView = null;
655
656        int end = mListPadding.top;
657
658        while (nextBottom > end && pos >= 0) {
659            // is this the selected item?
660            boolean selected = pos == mSelectedPosition;
661            View child = makeAndAddView(pos, nextBottom, false, mListPadding.left, selected);
662            nextBottom = child.getTop() - mDividerHeight;
663            if (selected) {
664                selectedView = child;
665            }
666            pos--;
667        }
668
669        mFirstPosition = pos + 1;
670
671        return selectedView;
672    }
673
674    /**
675     * Fills the list from top to bottom, starting with mFirstPosition
676     *
677     * @param nextTop The location where the top of the first item should be
678     *        drawn
679     *
680     * @return The view that is currently selected
681     */
682    private View fillFromTop(int nextTop) {
683        mFirstPosition = Math.min(mFirstPosition, mSelectedPosition);
684        mFirstPosition = Math.min(mFirstPosition, mItemCount - 1);
685        if (mFirstPosition < 0) {
686            mFirstPosition = 0;
687        }
688        return fillDown(mFirstPosition, nextTop);
689    }
690
691
692    /**
693     * Put mSelectedPosition in the middle of the screen and then build up and
694     * down from there. This method forces mSelectedPosition to the center.
695     *
696     * @param childrenTop Top of the area in which children can be drawn, as
697     *        measured in pixels
698     * @param childrenBottom Bottom of the area in which children can be drawn,
699     *        as measured in pixels
700     * @return Currently selected view
701     */
702    private View fillFromMiddle(int childrenTop, int childrenBottom) {
703        int height = childrenBottom - childrenTop;
704
705        int position = reconcileSelectedPosition();
706
707        View sel = makeAndAddView(position, childrenTop, true,
708                mListPadding.left, true);
709        mFirstPosition = position;
710
711        int selHeight = sel.getMeasuredHeight();
712        if (selHeight <= height) {
713            sel.offsetTopAndBottom((height - selHeight) / 2);
714        }
715
716        fillAboveAndBelow(sel, position);
717
718        if (!mStackFromBottom) {
719            correctTooHigh(getChildCount());
720        } else {
721            correctTooLow(getChildCount());
722        }
723
724        return sel;
725    }
726
727    /**
728     * Once the selected view as been placed, fill up the visible area above and
729     * below it.
730     *
731     * @param sel The selected view
732     * @param position The position corresponding to sel
733     */
734    private void fillAboveAndBelow(View sel, int position) {
735        final int dividerHeight = mDividerHeight;
736        if (!mStackFromBottom) {
737            fillUp(position - 1, sel.getTop() - dividerHeight);
738            adjustViewsUpOrDown();
739            fillDown(position + 1, sel.getBottom() + dividerHeight);
740        } else {
741            fillDown(position + 1, sel.getBottom() + dividerHeight);
742            adjustViewsUpOrDown();
743            fillUp(position - 1, sel.getTop() - dividerHeight);
744        }
745    }
746
747
748    /**
749     * Fills the grid based on positioning the new selection at a specific
750     * location. The selection may be moved so that it does not intersect the
751     * faded edges. The grid is then filled upwards and downwards from there.
752     *
753     * @param selectedTop Where the selected item should be
754     * @param childrenTop Where to start drawing children
755     * @param childrenBottom Last pixel where children can be drawn
756     * @return The view that currently has selection
757     */
758    private View fillFromSelection(int selectedTop, int childrenTop, int childrenBottom) {
759        int fadingEdgeLength = getVerticalFadingEdgeLength();
760        final int selectedPosition = mSelectedPosition;
761
762        View sel;
763
764        final int topSelectionPixel = getTopSelectionPixel(childrenTop, fadingEdgeLength,
765                selectedPosition);
766        final int bottomSelectionPixel = getBottomSelectionPixel(childrenBottom, fadingEdgeLength,
767                selectedPosition);
768
769        sel = makeAndAddView(selectedPosition, selectedTop, true, mListPadding.left, true);
770
771
772        // Some of the newly selected item extends below the bottom of the list
773        if (sel.getBottom() > bottomSelectionPixel) {
774            // Find space available above the selection into which we can scroll
775            // upwards
776            final int spaceAbove = sel.getTop() - topSelectionPixel;
777
778            // Find space required to bring the bottom of the selected item
779            // fully into view
780            final int spaceBelow = sel.getBottom() - bottomSelectionPixel;
781            final int offset = Math.min(spaceAbove, spaceBelow);
782
783            // Now offset the selected item to get it into view
784            sel.offsetTopAndBottom(-offset);
785        } else if (sel.getTop() < topSelectionPixel) {
786            // Find space required to bring the top of the selected item fully
787            // into view
788            final int spaceAbove = topSelectionPixel - sel.getTop();
789
790            // Find space available below the selection into which we can scroll
791            // downwards
792            final int spaceBelow = bottomSelectionPixel - sel.getBottom();
793            final int offset = Math.min(spaceAbove, spaceBelow);
794
795            // Offset the selected item to get it into view
796            sel.offsetTopAndBottom(offset);
797        }
798
799        // Fill in views above and below
800        fillAboveAndBelow(sel, selectedPosition);
801
802        if (!mStackFromBottom) {
803            correctTooHigh(getChildCount());
804        } else {
805            correctTooLow(getChildCount());
806        }
807
808        return sel;
809    }
810
811    /**
812     * Calculate the bottom-most pixel we can draw the selection into
813     *
814     * @param childrenBottom Bottom pixel were children can be drawn
815     * @param fadingEdgeLength Length of the fading edge in pixels, if present
816     * @param selectedPosition The position that will be selected
817     * @return The bottom-most pixel we can draw the selection into
818     */
819    private int getBottomSelectionPixel(int childrenBottom, int fadingEdgeLength,
820            int selectedPosition) {
821        int bottomSelectionPixel = childrenBottom;
822        if (selectedPosition != mItemCount - 1) {
823            bottomSelectionPixel -= fadingEdgeLength;
824        }
825        return bottomSelectionPixel;
826    }
827
828    /**
829     * Calculate the top-most pixel we can draw the selection into
830     *
831     * @param childrenTop Top pixel were children can be drawn
832     * @param fadingEdgeLength Length of the fading edge in pixels, if present
833     * @param selectedPosition The position that will be selected
834     * @return The top-most pixel we can draw the selection into
835     */
836    private int getTopSelectionPixel(int childrenTop, int fadingEdgeLength, int selectedPosition) {
837        // first pixel we can draw the selection into
838        int topSelectionPixel = childrenTop;
839        if (selectedPosition > 0) {
840            topSelectionPixel += fadingEdgeLength;
841        }
842        return topSelectionPixel;
843    }
844
845    /**
846     * Smoothly scroll to the specified adapter position. The view will
847     * scroll such that the indicated position is displayed.
848     * @param position Scroll to this adapter position.
849     */
850    @android.view.RemotableViewMethod
851    public void smoothScrollToPosition(int position) {
852        super.smoothScrollToPosition(position);
853    }
854
855    /**
856     * Smoothly scroll to the specified adapter position offset. The view will
857     * scroll such that the indicated position is displayed.
858     * @param offset The amount to offset from the adapter position to scroll to.
859     */
860    @android.view.RemotableViewMethod
861    public void smoothScrollByOffset(int offset) {
862        super.smoothScrollByOffset(offset);
863    }
864
865    /**
866     * Fills the list based on positioning the new selection relative to the old
867     * selection. The new selection will be placed at, above, or below the
868     * location of the new selection depending on how the selection is moving.
869     * The selection will then be pinned to the visible part of the screen,
870     * excluding the edges that are faded. The list is then filled upwards and
871     * downwards from there.
872     *
873     * @param oldSel The old selected view. Useful for trying to put the new
874     *        selection in the same place
875     * @param newSel The view that is to become selected. Useful for trying to
876     *        put the new selection in the same place
877     * @param delta Which way we are moving
878     * @param childrenTop Where to start drawing children
879     * @param childrenBottom Last pixel where children can be drawn
880     * @return The view that currently has selection
881     */
882    private View moveSelection(View oldSel, View newSel, int delta, int childrenTop,
883            int childrenBottom) {
884        int fadingEdgeLength = getVerticalFadingEdgeLength();
885        final int selectedPosition = mSelectedPosition;
886
887        View sel;
888
889        final int topSelectionPixel = getTopSelectionPixel(childrenTop, fadingEdgeLength,
890                selectedPosition);
891        final int bottomSelectionPixel = getBottomSelectionPixel(childrenTop, fadingEdgeLength,
892                selectedPosition);
893
894        if (delta > 0) {
895            /*
896             * Case 1: Scrolling down.
897             */
898
899            /*
900             *     Before           After
901             *    |       |        |       |
902             *    +-------+        +-------+
903             *    |   A   |        |   A   |
904             *    |   1   |   =>   +-------+
905             *    +-------+        |   B   |
906             *    |   B   |        |   2   |
907             *    +-------+        +-------+
908             *    |       |        |       |
909             *
910             *    Try to keep the top of the previously selected item where it was.
911             *    oldSel = A
912             *    sel = B
913             */
914
915            // Put oldSel (A) where it belongs
916            oldSel = makeAndAddView(selectedPosition - 1, oldSel.getTop(), true,
917                    mListPadding.left, false);
918
919            final int dividerHeight = mDividerHeight;
920
921            // Now put the new selection (B) below that
922            sel = makeAndAddView(selectedPosition, oldSel.getBottom() + dividerHeight, true,
923                    mListPadding.left, true);
924
925            // Some of the newly selected item extends below the bottom of the list
926            if (sel.getBottom() > bottomSelectionPixel) {
927
928                // Find space available above the selection into which we can scroll upwards
929                int spaceAbove = sel.getTop() - topSelectionPixel;
930
931                // Find space required to bring the bottom of the selected item fully into view
932                int spaceBelow = sel.getBottom() - bottomSelectionPixel;
933
934                // Don't scroll more than half the height of the list
935                int halfVerticalSpace = (childrenBottom - childrenTop) / 2;
936                int offset = Math.min(spaceAbove, spaceBelow);
937                offset = Math.min(offset, halfVerticalSpace);
938
939                // We placed oldSel, so offset that item
940                oldSel.offsetTopAndBottom(-offset);
941                // Now offset the selected item to get it into view
942                sel.offsetTopAndBottom(-offset);
943            }
944
945            // Fill in views above and below
946            if (!mStackFromBottom) {
947                fillUp(mSelectedPosition - 2, sel.getTop() - dividerHeight);
948                adjustViewsUpOrDown();
949                fillDown(mSelectedPosition + 1, sel.getBottom() + dividerHeight);
950            } else {
951                fillDown(mSelectedPosition + 1, sel.getBottom() + dividerHeight);
952                adjustViewsUpOrDown();
953                fillUp(mSelectedPosition - 2, sel.getTop() - dividerHeight);
954            }
955        } else if (delta < 0) {
956            /*
957             * Case 2: Scrolling up.
958             */
959
960            /*
961             *     Before           After
962             *    |       |        |       |
963             *    +-------+        +-------+
964             *    |   A   |        |   A   |
965             *    +-------+   =>   |   1   |
966             *    |   B   |        +-------+
967             *    |   2   |        |   B   |
968             *    +-------+        +-------+
969             *    |       |        |       |
970             *
971             *    Try to keep the top of the item about to become selected where it was.
972             *    newSel = A
973             *    olSel = B
974             */
975
976            if (newSel != null) {
977                // Try to position the top of newSel (A) where it was before it was selected
978                sel = makeAndAddView(selectedPosition, newSel.getTop(), true, mListPadding.left,
979                        true);
980            } else {
981                // If (A) was not on screen and so did not have a view, position
982                // it above the oldSel (B)
983                sel = makeAndAddView(selectedPosition, oldSel.getTop(), false, mListPadding.left,
984                        true);
985            }
986
987            // Some of the newly selected item extends above the top of the list
988            if (sel.getTop() < topSelectionPixel) {
989                // Find space required to bring the top of the selected item fully into view
990                int spaceAbove = topSelectionPixel - sel.getTop();
991
992               // Find space available below the selection into which we can scroll downwards
993                int spaceBelow = bottomSelectionPixel - sel.getBottom();
994
995                // Don't scroll more than half the height of the list
996                int halfVerticalSpace = (childrenBottom - childrenTop) / 2;
997                int offset = Math.min(spaceAbove, spaceBelow);
998                offset = Math.min(offset, halfVerticalSpace);
999
1000                // Offset the selected item to get it into view
1001                sel.offsetTopAndBottom(offset);
1002            }
1003
1004            // Fill in views above and below
1005            fillAboveAndBelow(sel, selectedPosition);
1006        } else {
1007
1008            int oldTop = oldSel.getTop();
1009
1010            /*
1011             * Case 3: Staying still
1012             */
1013            sel = makeAndAddView(selectedPosition, oldTop, true, mListPadding.left, true);
1014
1015            // We're staying still...
1016            if (oldTop < childrenTop) {
1017                // ... but the top of the old selection was off screen.
1018                // (This can happen if the data changes size out from under us)
1019                int newBottom = sel.getBottom();
1020                if (newBottom < childrenTop + 20) {
1021                    // Not enough visible -- bring it onscreen
1022                    sel.offsetTopAndBottom(childrenTop - sel.getTop());
1023                }
1024            }
1025
1026            // Fill in views above and below
1027            fillAboveAndBelow(sel, selectedPosition);
1028        }
1029
1030        return sel;
1031    }
1032
1033    private class FocusSelector implements Runnable {
1034        private int mPosition;
1035        private int mPositionTop;
1036
1037        public FocusSelector setup(int position, int top) {
1038            mPosition = position;
1039            mPositionTop = top;
1040            return this;
1041        }
1042
1043        public void run() {
1044            setSelectionFromTop(mPosition, mPositionTop);
1045        }
1046    }
1047
1048    @Override
1049    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1050        if (getChildCount() > 0) {
1051            View focusedChild = getFocusedChild();
1052            if (focusedChild != null) {
1053                final int childPosition = mFirstPosition + indexOfChild(focusedChild);
1054                final int childBottom = focusedChild.getBottom();
1055                final int offset = Math.max(0, childBottom - (h - mPaddingTop));
1056                final int top = focusedChild.getTop() - offset;
1057                if (mFocusSelector == null) {
1058                    mFocusSelector = new FocusSelector();
1059                }
1060                post(mFocusSelector.setup(childPosition, top));
1061            }
1062        }
1063        super.onSizeChanged(w, h, oldw, oldh);
1064    }
1065
1066    @Override
1067    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1068        // Sets up mListPadding
1069        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1070
1071        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
1072        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
1073        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
1074        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
1075
1076        int childWidth = 0;
1077        int childHeight = 0;
1078
1079        mItemCount = mAdapter == null ? 0 : mAdapter.getCount();
1080        if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED ||
1081                heightMode == MeasureSpec.UNSPECIFIED)) {
1082            final View child = obtainView(0, mIsScrap);
1083
1084            measureScrapChild(child, 0, widthMeasureSpec);
1085
1086            childWidth = child.getMeasuredWidth();
1087            childHeight = child.getMeasuredHeight();
1088
1089            if (recycleOnMeasure() && mRecycler.shouldRecycleViewType(
1090                    ((LayoutParams) child.getLayoutParams()).viewType)) {
1091                mRecycler.addScrapView(child);
1092            }
1093        }
1094
1095        if (widthMode == MeasureSpec.UNSPECIFIED) {
1096            widthSize = mListPadding.left + mListPadding.right + childWidth +
1097                    getVerticalScrollbarWidth();
1098        }
1099
1100        if (heightMode == MeasureSpec.UNSPECIFIED) {
1101            heightSize = mListPadding.top + mListPadding.bottom + childHeight +
1102                    getVerticalFadingEdgeLength() * 2;
1103        }
1104
1105        if (heightMode == MeasureSpec.AT_MOST) {
1106            // TODO: after first layout we should maybe start at the first visible position, not 0
1107            heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);
1108        }
1109
1110        setMeasuredDimension(widthSize, heightSize);
1111        mWidthMeasureSpec = widthMeasureSpec;
1112    }
1113
1114    private void measureScrapChild(View child, int position, int widthMeasureSpec) {
1115        LayoutParams p = (LayoutParams) child.getLayoutParams();
1116        if (p == null) {
1117            p = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1118                    ViewGroup.LayoutParams.WRAP_CONTENT, 0);
1119            child.setLayoutParams(p);
1120        }
1121        p.viewType = mAdapter.getItemViewType(position);
1122        p.forceAdd = true;
1123
1124        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec,
1125                mListPadding.left + mListPadding.right, p.width);
1126        int lpHeight = p.height;
1127        int childHeightSpec;
1128        if (lpHeight > 0) {
1129            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
1130        } else {
1131            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1132        }
1133        child.measure(childWidthSpec, childHeightSpec);
1134    }
1135
1136    /**
1137     * @return True to recycle the views used to measure this ListView in
1138     *         UNSPECIFIED/AT_MOST modes, false otherwise.
1139     * @hide
1140     */
1141    @ViewDebug.ExportedProperty(category = "list")
1142    protected boolean recycleOnMeasure() {
1143        return true;
1144    }
1145
1146    /**
1147     * Measures the height of the given range of children (inclusive) and
1148     * returns the height with this ListView's padding and divider heights
1149     * included. If maxHeight is provided, the measuring will stop when the
1150     * current height reaches maxHeight.
1151     *
1152     * @param widthMeasureSpec The width measure spec to be given to a child's
1153     *            {@link View#measure(int, int)}.
1154     * @param startPosition The position of the first child to be shown.
1155     * @param endPosition The (inclusive) position of the last child to be
1156     *            shown. Specify {@link #NO_POSITION} if the last child should be
1157     *            the last available child from the adapter.
1158     * @param maxHeight The maximum height that will be returned (if all the
1159     *            children don't fit in this value, this value will be
1160     *            returned).
1161     * @param disallowPartialChildPosition In general, whether the returned
1162     *            height should only contain entire children. This is more
1163     *            powerful--it is the first inclusive position at which partial
1164     *            children will not be allowed. Example: it looks nice to have
1165     *            at least 3 completely visible children, and in portrait this
1166     *            will most likely fit; but in landscape there could be times
1167     *            when even 2 children can not be completely shown, so a value
1168     *            of 2 (remember, inclusive) would be good (assuming
1169     *            startPosition is 0).
1170     * @return The height of this ListView with the given children.
1171     */
1172    final int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition,
1173            final int maxHeight, int disallowPartialChildPosition) {
1174
1175        final ListAdapter adapter = mAdapter;
1176        if (adapter == null) {
1177            return mListPadding.top + mListPadding.bottom;
1178        }
1179
1180        // Include the padding of the list
1181        int returnedHeight = mListPadding.top + mListPadding.bottom;
1182        final int dividerHeight = ((mDividerHeight > 0) && mDivider != null) ? mDividerHeight : 0;
1183        // The previous height value that was less than maxHeight and contained
1184        // no partial children
1185        int prevHeightWithoutPartialChild = 0;
1186        int i;
1187        View child;
1188
1189        // mItemCount - 1 since endPosition parameter is inclusive
1190        endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition;
1191        final AbsListView.RecycleBin recycleBin = mRecycler;
1192        final boolean recyle = recycleOnMeasure();
1193        final boolean[] isScrap = mIsScrap;
1194
1195        for (i = startPosition; i <= endPosition; ++i) {
1196            child = obtainView(i, isScrap);
1197
1198            measureScrapChild(child, i, widthMeasureSpec);
1199
1200            if (i > 0) {
1201                // Count the divider for all but one child
1202                returnedHeight += dividerHeight;
1203            }
1204
1205            // Recycle the view before we possibly return from the method
1206            if (recyle && recycleBin.shouldRecycleViewType(
1207                    ((LayoutParams) child.getLayoutParams()).viewType)) {
1208                recycleBin.addScrapView(child);
1209            }
1210
1211            returnedHeight += child.getMeasuredHeight();
1212
1213            if (returnedHeight >= maxHeight) {
1214                // We went over, figure out which height to return.  If returnedHeight > maxHeight,
1215                // then the i'th position did not fit completely.
1216                return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1)
1217                            && (i > disallowPartialChildPosition) // We've past the min pos
1218                            && (prevHeightWithoutPartialChild > 0) // We have a prev height
1219                            && (returnedHeight != maxHeight) // i'th child did not fit completely
1220                        ? prevHeightWithoutPartialChild
1221                        : maxHeight;
1222            }
1223
1224            if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) {
1225                prevHeightWithoutPartialChild = returnedHeight;
1226            }
1227        }
1228
1229        // At this point, we went through the range of children, and they each
1230        // completely fit, so return the returnedHeight
1231        return returnedHeight;
1232    }
1233
1234    @Override
1235    int findMotionRow(int y) {
1236        int childCount = getChildCount();
1237        if (childCount > 0) {
1238            if (!mStackFromBottom) {
1239                for (int i = 0; i < childCount; i++) {
1240                    View v = getChildAt(i);
1241                    if (y <= v.getBottom()) {
1242                        return mFirstPosition + i;
1243                    }
1244                }
1245            } else {
1246                for (int i = childCount - 1; i >= 0; i--) {
1247                    View v = getChildAt(i);
1248                    if (y >= v.getTop()) {
1249                        return mFirstPosition + i;
1250                    }
1251                }
1252            }
1253        }
1254        return INVALID_POSITION;
1255    }
1256
1257    /**
1258     * Put a specific item at a specific location on the screen and then build
1259     * up and down from there.
1260     *
1261     * @param position The reference view to use as the starting point
1262     * @param top Pixel offset from the top of this view to the top of the
1263     *        reference view.
1264     *
1265     * @return The selected view, or null if the selected view is outside the
1266     *         visible area.
1267     */
1268    private View fillSpecific(int position, int top) {
1269        boolean tempIsSelected = position == mSelectedPosition;
1270        View temp = makeAndAddView(position, top, true, mListPadding.left, tempIsSelected);
1271        // Possibly changed again in fillUp if we add rows above this one.
1272        mFirstPosition = position;
1273
1274        View above;
1275        View below;
1276
1277        final int dividerHeight = mDividerHeight;
1278        if (!mStackFromBottom) {
1279            above = fillUp(position - 1, temp.getTop() - dividerHeight);
1280            // This will correct for the top of the first view not touching the top of the list
1281            adjustViewsUpOrDown();
1282            below = fillDown(position + 1, temp.getBottom() + dividerHeight);
1283            int childCount = getChildCount();
1284            if (childCount > 0) {
1285                correctTooHigh(childCount);
1286            }
1287        } else {
1288            below = fillDown(position + 1, temp.getBottom() + dividerHeight);
1289            // This will correct for the bottom of the last view not touching the bottom of the list
1290            adjustViewsUpOrDown();
1291            above = fillUp(position - 1, temp.getTop() - dividerHeight);
1292            int childCount = getChildCount();
1293            if (childCount > 0) {
1294                 correctTooLow(childCount);
1295            }
1296        }
1297
1298        if (tempIsSelected) {
1299            return temp;
1300        } else if (above != null) {
1301            return above;
1302        } else {
1303            return below;
1304        }
1305    }
1306
1307    /**
1308     * Check if we have dragged the bottom of the list too high (we have pushed the
1309     * top element off the top of the screen when we did not need to). Correct by sliding
1310     * everything back down.
1311     *
1312     * @param childCount Number of children
1313     */
1314    private void correctTooHigh(int childCount) {
1315        // First see if the last item is visible. If it is not, it is OK for the
1316        // top of the list to be pushed up.
1317        int lastPosition = mFirstPosition + childCount - 1;
1318        if (lastPosition == mItemCount - 1 && childCount > 0) {
1319
1320            // Get the last child ...
1321            final View lastChild = getChildAt(childCount - 1);
1322
1323            // ... and its bottom edge
1324            final int lastBottom = lastChild.getBottom();
1325
1326            // This is bottom of our drawable area
1327            final int end = (mBottom - mTop) - mListPadding.bottom;
1328
1329            // This is how far the bottom edge of the last view is from the bottom of the
1330            // drawable area
1331            int bottomOffset = end - lastBottom;
1332            View firstChild = getChildAt(0);
1333            final int firstTop = firstChild.getTop();
1334
1335            // Make sure we are 1) Too high, and 2) Either there are more rows above the
1336            // first row or the first row is scrolled off the top of the drawable area
1337            if (bottomOffset > 0 && (mFirstPosition > 0 || firstTop < mListPadding.top))  {
1338                if (mFirstPosition == 0) {
1339                    // Don't pull the top too far down
1340                    bottomOffset = Math.min(bottomOffset, mListPadding.top - firstTop);
1341                }
1342                // Move everything down
1343                offsetChildrenTopAndBottom(bottomOffset);
1344                if (mFirstPosition > 0) {
1345                    // Fill the gap that was opened above mFirstPosition with more rows, if
1346                    // possible
1347                    fillUp(mFirstPosition - 1, firstChild.getTop() - mDividerHeight);
1348                    // Close up the remaining gap
1349                    adjustViewsUpOrDown();
1350                }
1351
1352            }
1353        }
1354    }
1355
1356    /**
1357     * Check if we have dragged the bottom of the list too low (we have pushed the
1358     * bottom element off the bottom of the screen when we did not need to). Correct by sliding
1359     * everything back up.
1360     *
1361     * @param childCount Number of children
1362     */
1363    private void correctTooLow(int childCount) {
1364        // First see if the first item is visible. If it is not, it is OK for the
1365        // bottom of the list to be pushed down.
1366        if (mFirstPosition == 0 && childCount > 0) {
1367
1368            // Get the first child ...
1369            final View firstChild = getChildAt(0);
1370
1371            // ... and its top edge
1372            final int firstTop = firstChild.getTop();
1373
1374            // This is top of our drawable area
1375            final int start = mListPadding.top;
1376
1377            // This is bottom of our drawable area
1378            final int end = (mBottom - mTop) - mListPadding.bottom;
1379
1380            // This is how far the top edge of the first view is from the top of the
1381            // drawable area
1382            int topOffset = firstTop - start;
1383            View lastChild = getChildAt(childCount - 1);
1384            final int lastBottom = lastChild.getBottom();
1385            int lastPosition = mFirstPosition + childCount - 1;
1386
1387            // Make sure we are 1) Too low, and 2) Either there are more rows below the
1388            // last row or the last row is scrolled off the bottom of the drawable area
1389            if (topOffset > 0) {
1390                if (lastPosition < mItemCount - 1 || lastBottom > end)  {
1391                    if (lastPosition == mItemCount - 1) {
1392                        // Don't pull the bottom too far up
1393                        topOffset = Math.min(topOffset, lastBottom - end);
1394                    }
1395                    // Move everything up
1396                    offsetChildrenTopAndBottom(-topOffset);
1397                    if (lastPosition < mItemCount - 1) {
1398                        // Fill the gap that was opened below the last position with more rows, if
1399                        // possible
1400                        fillDown(lastPosition + 1, lastChild.getBottom() + mDividerHeight);
1401                        // Close up the remaining gap
1402                        adjustViewsUpOrDown();
1403                    }
1404                } else if (lastPosition == mItemCount - 1) {
1405                    adjustViewsUpOrDown();
1406                }
1407            }
1408        }
1409    }
1410
1411    @Override
1412    protected void layoutChildren() {
1413        final boolean blockLayoutRequests = mBlockLayoutRequests;
1414        if (!blockLayoutRequests) {
1415            mBlockLayoutRequests = true;
1416        } else {
1417            return;
1418        }
1419
1420        try {
1421            super.layoutChildren();
1422
1423            invalidate();
1424
1425            if (mAdapter == null) {
1426                resetList();
1427                invokeOnItemScrollListener();
1428                return;
1429            }
1430
1431            int childrenTop = mListPadding.top;
1432            int childrenBottom = mBottom - mTop - mListPadding.bottom;
1433
1434            int childCount = getChildCount();
1435            int index = 0;
1436            int delta = 0;
1437
1438            View sel;
1439            View oldSel = null;
1440            View oldFirst = null;
1441            View newSel = null;
1442
1443            View focusLayoutRestoreView = null;
1444
1445            // Remember stuff we will need down below
1446            switch (mLayoutMode) {
1447            case LAYOUT_SET_SELECTION:
1448                index = mNextSelectedPosition - mFirstPosition;
1449                if (index >= 0 && index < childCount) {
1450                    newSel = getChildAt(index);
1451                }
1452                break;
1453            case LAYOUT_FORCE_TOP:
1454            case LAYOUT_FORCE_BOTTOM:
1455            case LAYOUT_SPECIFIC:
1456            case LAYOUT_SYNC:
1457                break;
1458            case LAYOUT_MOVE_SELECTION:
1459            default:
1460                // Remember the previously selected view
1461                index = mSelectedPosition - mFirstPosition;
1462                if (index >= 0 && index < childCount) {
1463                    oldSel = getChildAt(index);
1464                }
1465
1466                // Remember the previous first child
1467                oldFirst = getChildAt(0);
1468
1469                if (mNextSelectedPosition >= 0) {
1470                    delta = mNextSelectedPosition - mSelectedPosition;
1471                }
1472
1473                // Caution: newSel might be null
1474                newSel = getChildAt(index + delta);
1475            }
1476
1477
1478            boolean dataChanged = mDataChanged;
1479            if (dataChanged) {
1480                handleDataChanged();
1481            }
1482
1483            // Handle the empty set by removing all views that are visible
1484            // and calling it a day
1485            if (mItemCount == 0) {
1486                resetList();
1487                invokeOnItemScrollListener();
1488                return;
1489            } else if (mItemCount != mAdapter.getCount()) {
1490                throw new IllegalStateException("The content of the adapter has changed but "
1491                        + "ListView did not receive a notification. Make sure the content of "
1492                        + "your adapter is not modified from a background thread, but only "
1493                        + "from the UI thread. [in ListView(" + getId() + ", " + getClass()
1494                        + ") with Adapter(" + mAdapter.getClass() + ")]");
1495            }
1496
1497            setSelectedPositionInt(mNextSelectedPosition);
1498
1499            // Pull all children into the RecycleBin.
1500            // These views will be reused if possible
1501            final int firstPosition = mFirstPosition;
1502            final RecycleBin recycleBin = mRecycler;
1503
1504            // reset the focus restoration
1505            View focusLayoutRestoreDirectChild = null;
1506
1507
1508            // Don't put header or footer views into the Recycler. Those are
1509            // already cached in mHeaderViews;
1510            if (dataChanged) {
1511                for (int i = 0; i < childCount; i++) {
1512                    recycleBin.addScrapView(getChildAt(i));
1513                    if (ViewDebug.TRACE_RECYCLER) {
1514                        ViewDebug.trace(getChildAt(i),
1515                                ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, index, i);
1516                    }
1517                }
1518            } else {
1519                recycleBin.fillActiveViews(childCount, firstPosition);
1520            }
1521
1522            // take focus back to us temporarily to avoid the eventual
1523            // call to clear focus when removing the focused child below
1524            // from messing things up when ViewRoot assigns focus back
1525            // to someone else
1526            final View focusedChild = getFocusedChild();
1527            if (focusedChild != null) {
1528                // TODO: in some cases focusedChild.getParent() == null
1529
1530                // we can remember the focused view to restore after relayout if the
1531                // data hasn't changed, or if the focused position is a header or footer
1532                if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
1533                    focusLayoutRestoreDirectChild = focusedChild;
1534                    // remember the specific view that had focus
1535                    focusLayoutRestoreView = findFocus();
1536                    if (focusLayoutRestoreView != null) {
1537                        // tell it we are going to mess with it
1538                        focusLayoutRestoreView.onStartTemporaryDetach();
1539                    }
1540                }
1541                requestFocus();
1542            }
1543
1544            // Clear out old views
1545            detachAllViewsFromParent();
1546
1547            switch (mLayoutMode) {
1548            case LAYOUT_SET_SELECTION:
1549                if (newSel != null) {
1550                    sel = fillFromSelection(newSel.getTop(), childrenTop, childrenBottom);
1551                } else {
1552                    sel = fillFromMiddle(childrenTop, childrenBottom);
1553                }
1554                break;
1555            case LAYOUT_SYNC:
1556                sel = fillSpecific(mSyncPosition, mSpecificTop);
1557                break;
1558            case LAYOUT_FORCE_BOTTOM:
1559                sel = fillUp(mItemCount - 1, childrenBottom);
1560                adjustViewsUpOrDown();
1561                break;
1562            case LAYOUT_FORCE_TOP:
1563                mFirstPosition = 0;
1564                sel = fillFromTop(childrenTop);
1565                adjustViewsUpOrDown();
1566                break;
1567            case LAYOUT_SPECIFIC:
1568                sel = fillSpecific(reconcileSelectedPosition(), mSpecificTop);
1569                break;
1570            case LAYOUT_MOVE_SELECTION:
1571                sel = moveSelection(oldSel, newSel, delta, childrenTop, childrenBottom);
1572                break;
1573            default:
1574                if (childCount == 0) {
1575                    if (!mStackFromBottom) {
1576                        final int position = lookForSelectablePosition(0, true);
1577                        setSelectedPositionInt(position);
1578                        sel = fillFromTop(childrenTop);
1579                    } else {
1580                        final int position = lookForSelectablePosition(mItemCount - 1, false);
1581                        setSelectedPositionInt(position);
1582                        sel = fillUp(mItemCount - 1, childrenBottom);
1583                    }
1584                } else {
1585                    if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) {
1586                        sel = fillSpecific(mSelectedPosition,
1587                                oldSel == null ? childrenTop : oldSel.getTop());
1588                    } else if (mFirstPosition < mItemCount) {
1589                        sel = fillSpecific(mFirstPosition,
1590                                oldFirst == null ? childrenTop : oldFirst.getTop());
1591                    } else {
1592                        sel = fillSpecific(0, childrenTop);
1593                    }
1594                }
1595                break;
1596            }
1597
1598            // Flush any cached views that did not get reused above
1599            recycleBin.scrapActiveViews();
1600
1601            if (sel != null) {
1602                // the current selected item should get focus if items
1603                // are focusable
1604                if (mItemsCanFocus && hasFocus() && !sel.hasFocus()) {
1605                    final boolean focusWasTaken = (sel == focusLayoutRestoreDirectChild &&
1606                            focusLayoutRestoreView.requestFocus()) || sel.requestFocus();
1607                    if (!focusWasTaken) {
1608                        // selected item didn't take focus, fine, but still want
1609                        // to make sure something else outside of the selected view
1610                        // has focus
1611                        final View focused = getFocusedChild();
1612                        if (focused != null) {
1613                            focused.clearFocus();
1614                        }
1615                        positionSelector(sel);
1616                    } else {
1617                        sel.setSelected(false);
1618                        mSelectorRect.setEmpty();
1619                    }
1620                } else {
1621                    positionSelector(sel);
1622                }
1623                mSelectedTop = sel.getTop();
1624            } else {
1625                if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_SCROLL) {
1626                    View child = getChildAt(mMotionPosition - mFirstPosition);
1627                    if (child != null) positionSelector(child);
1628                } else {
1629                    mSelectedTop = 0;
1630                    mSelectorRect.setEmpty();
1631                }
1632
1633                // even if there is not selected position, we may need to restore
1634                // focus (i.e. something focusable in touch mode)
1635                if (hasFocus() && focusLayoutRestoreView != null) {
1636                    focusLayoutRestoreView.requestFocus();
1637                }
1638            }
1639
1640            // tell focus view we are done mucking with it, if it is still in
1641            // our view hierarchy.
1642            if (focusLayoutRestoreView != null
1643                    && focusLayoutRestoreView.getWindowToken() != null) {
1644                focusLayoutRestoreView.onFinishTemporaryDetach();
1645            }
1646
1647            mLayoutMode = LAYOUT_NORMAL;
1648            mDataChanged = false;
1649            mNeedSync = false;
1650            setNextSelectedPositionInt(mSelectedPosition);
1651
1652            updateScrollIndicators();
1653
1654            if (mItemCount > 0) {
1655                checkSelectionChanged();
1656            }
1657
1658            invokeOnItemScrollListener();
1659        } finally {
1660            if (!blockLayoutRequests) {
1661                mBlockLayoutRequests = false;
1662            }
1663        }
1664    }
1665
1666    /**
1667     * @param child a direct child of this list.
1668     * @return Whether child is a header or footer view.
1669     */
1670    private boolean isDirectChildHeaderOrFooter(View child) {
1671
1672        final ArrayList<FixedViewInfo> headers = mHeaderViewInfos;
1673        final int numHeaders = headers.size();
1674        for (int i = 0; i < numHeaders; i++) {
1675            if (child == headers.get(i).view) {
1676                return true;
1677            }
1678        }
1679        final ArrayList<FixedViewInfo> footers = mFooterViewInfos;
1680        final int numFooters = footers.size();
1681        for (int i = 0; i < numFooters; i++) {
1682            if (child == footers.get(i).view) {
1683                return true;
1684            }
1685        }
1686        return false;
1687    }
1688
1689    /**
1690     * Obtain the view and add it to our list of children. The view can be made
1691     * fresh, converted from an unused view, or used as is if it was in the
1692     * recycle bin.
1693     *
1694     * @param position Logical position in the list
1695     * @param y Top or bottom edge of the view to add
1696     * @param flow If flow is true, align top edge to y. If false, align bottom
1697     *        edge to y.
1698     * @param childrenLeft Left edge where children should be positioned
1699     * @param selected Is this position selected?
1700     * @return View that was added
1701     */
1702    private View makeAndAddView(int position, int y, boolean flow, int childrenLeft,
1703            boolean selected) {
1704        View child;
1705
1706
1707        if (!mDataChanged) {
1708            // Try to use an exsiting view for this position
1709            child = mRecycler.getActiveView(position);
1710            if (child != null) {
1711                if (ViewDebug.TRACE_RECYCLER) {
1712                    ViewDebug.trace(child, ViewDebug.RecyclerTraceType.RECYCLE_FROM_ACTIVE_HEAP,
1713                            position, getChildCount());
1714                }
1715
1716                // Found it -- we're using an existing child
1717                // This just needs to be positioned
1718                setupChild(child, position, y, flow, childrenLeft, selected, true);
1719
1720                return child;
1721            }
1722        }
1723
1724        // Make a new view for this position, or convert an unused view if possible
1725        child = obtainView(position, mIsScrap);
1726
1727        // This needs to be positioned and measured
1728        setupChild(child, position, y, flow, childrenLeft, selected, mIsScrap[0]);
1729
1730        return child;
1731    }
1732
1733    /**
1734     * Add a view as a child and make sure it is measured (if necessary) and
1735     * positioned properly.
1736     *
1737     * @param child The view to add
1738     * @param position The position of this child
1739     * @param y The y position relative to which this view will be positioned
1740     * @param flowDown If true, align top edge to y. If false, align bottom
1741     *        edge to y.
1742     * @param childrenLeft Left edge where children should be positioned
1743     * @param selected Is this position selected?
1744     * @param recycled Has this view been pulled from the recycle bin? If so it
1745     *        does not need to be remeasured.
1746     */
1747    private void setupChild(View child, int position, int y, boolean flowDown, int childrenLeft,
1748            boolean selected, boolean recycled) {
1749        final boolean isSelected = selected && shouldShowSelector();
1750        final boolean updateChildSelected = isSelected != child.isSelected();
1751        final int mode = mTouchMode;
1752        final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL &&
1753                mMotionPosition == position;
1754        final boolean updateChildPressed = isPressed != child.isPressed();
1755        final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();
1756
1757        // Respect layout params that are already in the view. Otherwise make some up...
1758        // noinspection unchecked
1759        AbsListView.LayoutParams p = (AbsListView.LayoutParams) child.getLayoutParams();
1760        if (p == null) {
1761            p = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1762                    ViewGroup.LayoutParams.WRAP_CONTENT, 0);
1763        }
1764        p.viewType = mAdapter.getItemViewType(position);
1765
1766        if ((recycled && !p.forceAdd) || (p.recycledHeaderFooter &&
1767                p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) {
1768            attachViewToParent(child, flowDown ? -1 : 0, p);
1769        } else {
1770            p.forceAdd = false;
1771            if (p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
1772                p.recycledHeaderFooter = true;
1773            }
1774            addViewInLayout(child, flowDown ? -1 : 0, p, true);
1775        }
1776
1777        if (updateChildSelected) {
1778            child.setSelected(isSelected);
1779        }
1780
1781        if (updateChildPressed) {
1782            child.setPressed(isPressed);
1783        }
1784
1785        if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
1786            if (child instanceof Checkable) {
1787                ((Checkable) child).setChecked(mCheckStates.get(position));
1788            }
1789        }
1790
1791        if (needToMeasure) {
1792            int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
1793                    mListPadding.left + mListPadding.right, p.width);
1794            int lpHeight = p.height;
1795            int childHeightSpec;
1796            if (lpHeight > 0) {
1797                childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
1798            } else {
1799                childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1800            }
1801            child.measure(childWidthSpec, childHeightSpec);
1802        } else {
1803            cleanupLayoutState(child);
1804        }
1805
1806        final int w = child.getMeasuredWidth();
1807        final int h = child.getMeasuredHeight();
1808        final int childTop = flowDown ? y : y - h;
1809
1810        if (needToMeasure) {
1811            final int childRight = childrenLeft + w;
1812            final int childBottom = childTop + h;
1813            child.layout(childrenLeft, childTop, childRight, childBottom);
1814        } else {
1815            child.offsetLeftAndRight(childrenLeft - child.getLeft());
1816            child.offsetTopAndBottom(childTop - child.getTop());
1817        }
1818
1819        if (mCachingStarted && !child.isDrawingCacheEnabled()) {
1820            child.setDrawingCacheEnabled(true);
1821        }
1822    }
1823
1824    @Override
1825    protected boolean canAnimate() {
1826        return super.canAnimate() && mItemCount > 0;
1827    }
1828
1829    /**
1830     * Sets the currently selected item. If in touch mode, the item will not be selected
1831     * but it will still be positioned appropriately. If the specified selection position
1832     * is less than 0, then the item at position 0 will be selected.
1833     *
1834     * @param position Index (starting at 0) of the data item to be selected.
1835     */
1836    @Override
1837    public void setSelection(int position) {
1838        setSelectionFromTop(position, 0);
1839    }
1840
1841    /**
1842     * Sets the selected item and positions the selection y pixels from the top edge
1843     * of the ListView. (If in touch mode, the item will not be selected but it will
1844     * still be positioned appropriately.)
1845     *
1846     * @param position Index (starting at 0) of the data item to be selected.
1847     * @param y The distance from the top edge of the ListView (plus padding) that the
1848     *        item will be positioned.
1849     */
1850    public void setSelectionFromTop(int position, int y) {
1851        if (mAdapter == null) {
1852            return;
1853        }
1854
1855        if (!isInTouchMode()) {
1856            position = lookForSelectablePosition(position, true);
1857            if (position >= 0) {
1858                setNextSelectedPositionInt(position);
1859            }
1860        } else {
1861            mResurrectToPosition = position;
1862        }
1863
1864        if (position >= 0) {
1865            mLayoutMode = LAYOUT_SPECIFIC;
1866            mSpecificTop = mListPadding.top + y;
1867
1868            if (mNeedSync) {
1869                mSyncPosition = position;
1870                mSyncRowId = mAdapter.getItemId(position);
1871            }
1872
1873            requestLayout();
1874        }
1875    }
1876
1877    /**
1878     * Makes the item at the supplied position selected.
1879     *
1880     * @param position the position of the item to select
1881     */
1882    @Override
1883    void setSelectionInt(int position) {
1884        setNextSelectedPositionInt(position);
1885        boolean awakeScrollbars = false;
1886
1887        final int selectedPosition = mSelectedPosition;
1888
1889        if (selectedPosition >= 0) {
1890            if (position == selectedPosition - 1) {
1891                awakeScrollbars = true;
1892            } else if (position == selectedPosition + 1) {
1893                awakeScrollbars = true;
1894            }
1895        }
1896
1897        layoutChildren();
1898
1899        if (awakeScrollbars) {
1900            awakenScrollBars();
1901        }
1902    }
1903
1904    /**
1905     * Find a position that can be selected (i.e., is not a separator).
1906     *
1907     * @param position The starting position to look at.
1908     * @param lookDown Whether to look down for other positions.
1909     * @return The next selectable position starting at position and then searching either up or
1910     *         down. Returns {@link #INVALID_POSITION} if nothing can be found.
1911     */
1912    @Override
1913    int lookForSelectablePosition(int position, boolean lookDown) {
1914        final ListAdapter adapter = mAdapter;
1915        if (adapter == null || isInTouchMode()) {
1916            return INVALID_POSITION;
1917        }
1918
1919        final int count = adapter.getCount();
1920        if (!mAreAllItemsSelectable) {
1921            if (lookDown) {
1922                position = Math.max(0, position);
1923                while (position < count && !adapter.isEnabled(position)) {
1924                    position++;
1925                }
1926            } else {
1927                position = Math.min(position, count - 1);
1928                while (position >= 0 && !adapter.isEnabled(position)) {
1929                    position--;
1930                }
1931            }
1932
1933            if (position < 0 || position >= count) {
1934                return INVALID_POSITION;
1935            }
1936            return position;
1937        } else {
1938            if (position < 0 || position >= count) {
1939                return INVALID_POSITION;
1940            }
1941            return position;
1942        }
1943    }
1944
1945    @Override
1946    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1947        boolean populated = super.dispatchPopulateAccessibilityEvent(event);
1948
1949        // If the item count is less than 15 then subtract disabled items from the count and
1950        // position. Otherwise ignore disabled items.
1951        if (!populated) {
1952            int itemCount = 0;
1953            int currentItemIndex = getSelectedItemPosition();
1954
1955            ListAdapter adapter = getAdapter();
1956            if (adapter != null) {
1957                final int count = adapter.getCount();
1958                if (count < 15) {
1959                    for (int i = 0; i < count; i++) {
1960                        if (adapter.isEnabled(i)) {
1961                            itemCount++;
1962                        } else if (i <= currentItemIndex) {
1963                            currentItemIndex--;
1964                        }
1965                    }
1966                } else {
1967                    itemCount = count;
1968                }
1969            }
1970
1971            event.setItemCount(itemCount);
1972            event.setCurrentItemIndex(currentItemIndex);
1973        }
1974
1975        return populated;
1976    }
1977
1978    /**
1979     * setSelectionAfterHeaderView set the selection to be the first list item
1980     * after the header views.
1981     */
1982    public void setSelectionAfterHeaderView() {
1983        final int count = mHeaderViewInfos.size();
1984        if (count > 0) {
1985            mNextSelectedPosition = 0;
1986            return;
1987        }
1988
1989        if (mAdapter != null) {
1990            setSelection(count);
1991        } else {
1992            mNextSelectedPosition = count;
1993            mLayoutMode = LAYOUT_SET_SELECTION;
1994        }
1995
1996    }
1997
1998    @Override
1999    public boolean dispatchKeyEvent(KeyEvent event) {
2000        // Dispatch in the normal way
2001        boolean handled = super.dispatchKeyEvent(event);
2002        if (!handled) {
2003            // If we didn't handle it...
2004            View focused = getFocusedChild();
2005            if (focused != null && event.getAction() == KeyEvent.ACTION_DOWN) {
2006                // ... and our focused child didn't handle it
2007                // ... give it to ourselves so we can scroll if necessary
2008                handled = onKeyDown(event.getKeyCode(), event);
2009            }
2010        }
2011        return handled;
2012    }
2013
2014    @Override
2015    public boolean onKeyDown(int keyCode, KeyEvent event) {
2016        return commonKey(keyCode, 1, event);
2017    }
2018
2019    @Override
2020    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2021        return commonKey(keyCode, repeatCount, event);
2022    }
2023
2024    @Override
2025    public boolean onKeyUp(int keyCode, KeyEvent event) {
2026        return commonKey(keyCode, 1, event);
2027    }
2028
2029    private boolean commonKey(int keyCode, int count, KeyEvent event) {
2030        if (mAdapter == null) {
2031            return false;
2032        }
2033
2034        if (mDataChanged) {
2035            layoutChildren();
2036        }
2037
2038        boolean handled = false;
2039        int action = event.getAction();
2040
2041        if (action != KeyEvent.ACTION_UP) {
2042            if (mSelectedPosition < 0) {
2043                switch (keyCode) {
2044                case KeyEvent.KEYCODE_DPAD_UP:
2045                case KeyEvent.KEYCODE_DPAD_DOWN:
2046                case KeyEvent.KEYCODE_DPAD_CENTER:
2047                case KeyEvent.KEYCODE_ENTER:
2048                case KeyEvent.KEYCODE_SPACE:
2049                    if (resurrectSelection()) {
2050                        return true;
2051                    }
2052                }
2053            }
2054            switch (keyCode) {
2055            case KeyEvent.KEYCODE_DPAD_UP:
2056                if (!event.isAltPressed()) {
2057                    while (count > 0) {
2058                        handled = arrowScroll(FOCUS_UP);
2059                        count--;
2060                    }
2061                } else {
2062                    handled = fullScroll(FOCUS_UP);
2063                }
2064                break;
2065
2066            case KeyEvent.KEYCODE_DPAD_DOWN:
2067                if (!event.isAltPressed()) {
2068                    while (count > 0) {
2069                        handled = arrowScroll(FOCUS_DOWN);
2070                        count--;
2071                    }
2072                } else {
2073                    handled = fullScroll(FOCUS_DOWN);
2074                }
2075                break;
2076
2077            case KeyEvent.KEYCODE_DPAD_LEFT:
2078                handled = handleHorizontalFocusWithinListItem(View.FOCUS_LEFT);
2079                break;
2080            case KeyEvent.KEYCODE_DPAD_RIGHT:
2081                handled = handleHorizontalFocusWithinListItem(View.FOCUS_RIGHT);
2082                break;
2083
2084            case KeyEvent.KEYCODE_DPAD_CENTER:
2085            case KeyEvent.KEYCODE_ENTER:
2086                if (mItemCount > 0 && event.getRepeatCount() == 0) {
2087                    keyPressed();
2088                }
2089                handled = true;
2090                break;
2091
2092            case KeyEvent.KEYCODE_SPACE:
2093                if (mPopup == null || !mPopup.isShowing()) {
2094                    if (!event.isShiftPressed()) {
2095                        pageScroll(FOCUS_DOWN);
2096                    } else {
2097                        pageScroll(FOCUS_UP);
2098                    }
2099                    handled = true;
2100                }
2101                break;
2102            }
2103        }
2104
2105        if (!handled) {
2106            handled = sendToTextFilter(keyCode, count, event);
2107        }
2108
2109        if (handled) {
2110            return true;
2111        } else {
2112            switch (action) {
2113                case KeyEvent.ACTION_DOWN:
2114                    return super.onKeyDown(keyCode, event);
2115
2116                case KeyEvent.ACTION_UP:
2117                    return super.onKeyUp(keyCode, event);
2118
2119                case KeyEvent.ACTION_MULTIPLE:
2120                    return super.onKeyMultiple(keyCode, count, event);
2121
2122                default: // shouldn't happen
2123                    return false;
2124            }
2125        }
2126    }
2127
2128    /**
2129     * Scrolls up or down by the number of items currently present on screen.
2130     *
2131     * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2132     * @return whether selection was moved
2133     */
2134    boolean pageScroll(int direction) {
2135        int nextPage = -1;
2136        boolean down = false;
2137
2138        if (direction == FOCUS_UP) {
2139            nextPage = Math.max(0, mSelectedPosition - getChildCount() - 1);
2140        } else if (direction == FOCUS_DOWN) {
2141            nextPage = Math.min(mItemCount - 1, mSelectedPosition + getChildCount() - 1);
2142            down = true;
2143        }
2144
2145        if (nextPage >= 0) {
2146            int position = lookForSelectablePosition(nextPage, down);
2147            if (position >= 0) {
2148                mLayoutMode = LAYOUT_SPECIFIC;
2149                mSpecificTop = mPaddingTop + getVerticalFadingEdgeLength();
2150
2151                if (down && position > mItemCount - getChildCount()) {
2152                    mLayoutMode = LAYOUT_FORCE_BOTTOM;
2153                }
2154
2155                if (!down && position < getChildCount()) {
2156                    mLayoutMode = LAYOUT_FORCE_TOP;
2157                }
2158
2159                setSelectionInt(position);
2160                invokeOnItemScrollListener();
2161                if (!awakenScrollBars()) {
2162                    invalidate();
2163                }
2164
2165                return true;
2166            }
2167        }
2168
2169        return false;
2170    }
2171
2172    /**
2173     * Go to the last or first item if possible (not worrying about panning across or navigating
2174     * within the internal focus of the currently selected item.)
2175     *
2176     * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2177     *
2178     * @return whether selection was moved
2179     */
2180    boolean fullScroll(int direction) {
2181        boolean moved = false;
2182        if (direction == FOCUS_UP) {
2183            if (mSelectedPosition != 0) {
2184                int position = lookForSelectablePosition(0, true);
2185                if (position >= 0) {
2186                    mLayoutMode = LAYOUT_FORCE_TOP;
2187                    setSelectionInt(position);
2188                    invokeOnItemScrollListener();
2189                }
2190                moved = true;
2191            }
2192        } else if (direction == FOCUS_DOWN) {
2193            if (mSelectedPosition < mItemCount - 1) {
2194                int position = lookForSelectablePosition(mItemCount - 1, true);
2195                if (position >= 0) {
2196                    mLayoutMode = LAYOUT_FORCE_BOTTOM;
2197                    setSelectionInt(position);
2198                    invokeOnItemScrollListener();
2199                }
2200                moved = true;
2201            }
2202        }
2203
2204        if (moved && !awakenScrollBars()) {
2205            awakenScrollBars();
2206            invalidate();
2207        }
2208
2209        return moved;
2210    }
2211
2212    /**
2213     * To avoid horizontal focus searches changing the selected item, we
2214     * manually focus search within the selected item (as applicable), and
2215     * prevent focus from jumping to something within another item.
2216     * @param direction one of {View.FOCUS_LEFT, View.FOCUS_RIGHT}
2217     * @return Whether this consumes the key event.
2218     */
2219    private boolean handleHorizontalFocusWithinListItem(int direction) {
2220        if (direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT)  {
2221            throw new IllegalArgumentException("direction must be one of"
2222                    + " {View.FOCUS_LEFT, View.FOCUS_RIGHT}");
2223        }
2224
2225        final int numChildren = getChildCount();
2226        if (mItemsCanFocus && numChildren > 0 && mSelectedPosition != INVALID_POSITION) {
2227            final View selectedView = getSelectedView();
2228            if (selectedView != null && selectedView.hasFocus() &&
2229                    selectedView instanceof ViewGroup) {
2230
2231                final View currentFocus = selectedView.findFocus();
2232                final View nextFocus = FocusFinder.getInstance().findNextFocus(
2233                        (ViewGroup) selectedView, currentFocus, direction);
2234                if (nextFocus != null) {
2235                    // do the math to get interesting rect in next focus' coordinates
2236                    currentFocus.getFocusedRect(mTempRect);
2237                    offsetDescendantRectToMyCoords(currentFocus, mTempRect);
2238                    offsetRectIntoDescendantCoords(nextFocus, mTempRect);
2239                    if (nextFocus.requestFocus(direction, mTempRect)) {
2240                        return true;
2241                    }
2242                }
2243                // we are blocking the key from being handled (by returning true)
2244                // if the global result is going to be some other view within this
2245                // list.  this is to acheive the overall goal of having
2246                // horizontal d-pad navigation remain in the current item.
2247                final View globalNextFocus = FocusFinder.getInstance().findNextFocus(
2248                        (ViewGroup) getRootView(), currentFocus, direction);
2249                if (globalNextFocus != null) {
2250                    return isViewAncestorOf(globalNextFocus, this);
2251                }
2252            }
2253        }
2254        return false;
2255    }
2256
2257    /**
2258     * Scrolls to the next or previous item if possible.
2259     *
2260     * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2261     *
2262     * @return whether selection was moved
2263     */
2264    boolean arrowScroll(int direction) {
2265        try {
2266            mInLayout = true;
2267            final boolean handled = arrowScrollImpl(direction);
2268            if (handled) {
2269                playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2270            }
2271            return handled;
2272        } finally {
2273            mInLayout = false;
2274        }
2275    }
2276
2277    /**
2278     * Handle an arrow scroll going up or down.  Take into account whether items are selectable,
2279     * whether there are focusable items etc.
2280     *
2281     * @param direction Either {@link android.view.View#FOCUS_UP} or {@link android.view.View#FOCUS_DOWN}.
2282     * @return Whether any scrolling, selection or focus change occured.
2283     */
2284    private boolean arrowScrollImpl(int direction) {
2285        if (getChildCount() <= 0) {
2286            return false;
2287        }
2288
2289        View selectedView = getSelectedView();
2290
2291        int nextSelectedPosition = lookForSelectablePositionOnScreen(direction);
2292        int amountToScroll = amountToScroll(direction, nextSelectedPosition);
2293
2294        // if we are moving focus, we may OVERRIDE the default behavior
2295        final ArrowScrollFocusResult focusResult = mItemsCanFocus ? arrowScrollFocused(direction) : null;
2296        if (focusResult != null) {
2297            nextSelectedPosition = focusResult.getSelectedPosition();
2298            amountToScroll = focusResult.getAmountToScroll();
2299        }
2300
2301        boolean needToRedraw = focusResult != null;
2302        if (nextSelectedPosition != INVALID_POSITION) {
2303            handleNewSelectionChange(selectedView, direction, nextSelectedPosition, focusResult != null);
2304            setSelectedPositionInt(nextSelectedPosition);
2305            setNextSelectedPositionInt(nextSelectedPosition);
2306            selectedView = getSelectedView();
2307            if (mItemsCanFocus && focusResult == null) {
2308                // there was no new view found to take focus, make sure we
2309                // don't leave focus with the old selection
2310                final View focused = getFocusedChild();
2311                if (focused != null) {
2312                    focused.clearFocus();
2313                }
2314            }
2315            needToRedraw = true;
2316            checkSelectionChanged();
2317        }
2318
2319        if (amountToScroll > 0) {
2320            scrollListItemsBy((direction == View.FOCUS_UP) ? amountToScroll : -amountToScroll);
2321            needToRedraw = true;
2322        }
2323
2324        // if we didn't find a new focusable, make sure any existing focused
2325        // item that was panned off screen gives up focus.
2326        if (mItemsCanFocus && (focusResult == null)
2327                && selectedView != null && selectedView.hasFocus()) {
2328            final View focused = selectedView.findFocus();
2329            if (distanceToView(focused) > 0) {
2330                focused.clearFocus();
2331            }
2332        }
2333
2334        // if  the current selection is panned off, we need to remove the selection
2335        if (nextSelectedPosition == INVALID_POSITION && selectedView != null
2336                && !isViewAncestorOf(selectedView, this)) {
2337            selectedView = null;
2338            hideSelector();
2339
2340            // but we don't want to set the ressurect position (that would make subsequent
2341            // unhandled key events bring back the item we just scrolled off!)
2342            mResurrectToPosition = INVALID_POSITION;
2343        }
2344
2345        if (needToRedraw) {
2346            if (selectedView != null) {
2347                positionSelector(selectedView);
2348                mSelectedTop = selectedView.getTop();
2349            }
2350            if (!awakenScrollBars()) {
2351                invalidate();
2352            }
2353            invokeOnItemScrollListener();
2354            return true;
2355        }
2356
2357        return false;
2358    }
2359
2360    /**
2361     * When selection changes, it is possible that the previously selected or the
2362     * next selected item will change its size.  If so, we need to offset some folks,
2363     * and re-layout the items as appropriate.
2364     *
2365     * @param selectedView The currently selected view (before changing selection).
2366     *   should be <code>null</code> if there was no previous selection.
2367     * @param direction Either {@link android.view.View#FOCUS_UP} or
2368     *        {@link android.view.View#FOCUS_DOWN}.
2369     * @param newSelectedPosition The position of the next selection.
2370     * @param newFocusAssigned whether new focus was assigned.  This matters because
2371     *        when something has focus, we don't want to show selection (ugh).
2372     */
2373    private void handleNewSelectionChange(View selectedView, int direction, int newSelectedPosition,
2374            boolean newFocusAssigned) {
2375        if (newSelectedPosition == INVALID_POSITION) {
2376            throw new IllegalArgumentException("newSelectedPosition needs to be valid");
2377        }
2378
2379        // whether or not we are moving down or up, we want to preserve the
2380        // top of whatever view is on top:
2381        // - moving down: the view that had selection
2382        // - moving up: the view that is getting selection
2383        View topView;
2384        View bottomView;
2385        int topViewIndex, bottomViewIndex;
2386        boolean topSelected = false;
2387        final int selectedIndex = mSelectedPosition - mFirstPosition;
2388        final int nextSelectedIndex = newSelectedPosition - mFirstPosition;
2389        if (direction == View.FOCUS_UP) {
2390            topViewIndex = nextSelectedIndex;
2391            bottomViewIndex = selectedIndex;
2392            topView = getChildAt(topViewIndex);
2393            bottomView = selectedView;
2394            topSelected = true;
2395        } else {
2396            topViewIndex = selectedIndex;
2397            bottomViewIndex = nextSelectedIndex;
2398            topView = selectedView;
2399            bottomView = getChildAt(bottomViewIndex);
2400        }
2401
2402        final int numChildren = getChildCount();
2403
2404        // start with top view: is it changing size?
2405        if (topView != null) {
2406            topView.setSelected(!newFocusAssigned && topSelected);
2407            measureAndAdjustDown(topView, topViewIndex, numChildren);
2408        }
2409
2410        // is the bottom view changing size?
2411        if (bottomView != null) {
2412            bottomView.setSelected(!newFocusAssigned && !topSelected);
2413            measureAndAdjustDown(bottomView, bottomViewIndex, numChildren);
2414        }
2415    }
2416
2417    /**
2418     * Re-measure a child, and if its height changes, lay it out preserving its
2419     * top, and adjust the children below it appropriately.
2420     * @param child The child
2421     * @param childIndex The view group index of the child.
2422     * @param numChildren The number of children in the view group.
2423     */
2424    private void measureAndAdjustDown(View child, int childIndex, int numChildren) {
2425        int oldHeight = child.getHeight();
2426        measureItem(child);
2427        if (child.getMeasuredHeight() != oldHeight) {
2428            // lay out the view, preserving its top
2429            relayoutMeasuredItem(child);
2430
2431            // adjust views below appropriately
2432            final int heightDelta = child.getMeasuredHeight() - oldHeight;
2433            for (int i = childIndex + 1; i < numChildren; i++) {
2434                getChildAt(i).offsetTopAndBottom(heightDelta);
2435            }
2436        }
2437    }
2438
2439    /**
2440     * Measure a particular list child.
2441     * TODO: unify with setUpChild.
2442     * @param child The child.
2443     */
2444    private void measureItem(View child) {
2445        ViewGroup.LayoutParams p = child.getLayoutParams();
2446        if (p == null) {
2447            p = new ViewGroup.LayoutParams(
2448                    ViewGroup.LayoutParams.MATCH_PARENT,
2449                    ViewGroup.LayoutParams.WRAP_CONTENT);
2450        }
2451
2452        int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
2453                mListPadding.left + mListPadding.right, p.width);
2454        int lpHeight = p.height;
2455        int childHeightSpec;
2456        if (lpHeight > 0) {
2457            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
2458        } else {
2459            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
2460        }
2461        child.measure(childWidthSpec, childHeightSpec);
2462    }
2463
2464    /**
2465     * Layout a child that has been measured, preserving its top position.
2466     * TODO: unify with setUpChild.
2467     * @param child The child.
2468     */
2469    private void relayoutMeasuredItem(View child) {
2470        final int w = child.getMeasuredWidth();
2471        final int h = child.getMeasuredHeight();
2472        final int childLeft = mListPadding.left;
2473        final int childRight = childLeft + w;
2474        final int childTop = child.getTop();
2475        final int childBottom = childTop + h;
2476        child.layout(childLeft, childTop, childRight, childBottom);
2477    }
2478
2479    /**
2480     * @return The amount to preview next items when arrow srolling.
2481     */
2482    private int getArrowScrollPreviewLength() {
2483        return Math.max(MIN_SCROLL_PREVIEW_PIXELS, getVerticalFadingEdgeLength());
2484    }
2485
2486    /**
2487     * Determine how much we need to scroll in order to get the next selected view
2488     * visible, with a fading edge showing below as applicable.  The amount is
2489     * capped at {@link #getMaxScrollAmount()} .
2490     *
2491     * @param direction either {@link android.view.View#FOCUS_UP} or
2492     *        {@link android.view.View#FOCUS_DOWN}.
2493     * @param nextSelectedPosition The position of the next selection, or
2494     *        {@link #INVALID_POSITION} if there is no next selectable position
2495     * @return The amount to scroll. Note: this is always positive!  Direction
2496     *         needs to be taken into account when actually scrolling.
2497     */
2498    private int amountToScroll(int direction, int nextSelectedPosition) {
2499        final int listBottom = getHeight() - mListPadding.bottom;
2500        final int listTop = mListPadding.top;
2501
2502        final int numChildren = getChildCount();
2503
2504        if (direction == View.FOCUS_DOWN) {
2505            int indexToMakeVisible = numChildren - 1;
2506            if (nextSelectedPosition != INVALID_POSITION) {
2507                indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2508            }
2509
2510            final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2511            final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2512
2513            int goalBottom = listBottom;
2514            if (positionToMakeVisible < mItemCount - 1) {
2515                goalBottom -= getArrowScrollPreviewLength();
2516            }
2517
2518            if (viewToMakeVisible.getBottom() <= goalBottom) {
2519                // item is fully visible.
2520                return 0;
2521            }
2522
2523            if (nextSelectedPosition != INVALID_POSITION
2524                    && (goalBottom - viewToMakeVisible.getTop()) >= getMaxScrollAmount()) {
2525                // item already has enough of it visible, changing selection is good enough
2526                return 0;
2527            }
2528
2529            int amountToScroll = (viewToMakeVisible.getBottom() - goalBottom);
2530
2531            if ((mFirstPosition + numChildren) == mItemCount) {
2532                // last is last in list -> make sure we don't scroll past it
2533                final int max = getChildAt(numChildren - 1).getBottom() - listBottom;
2534                amountToScroll = Math.min(amountToScroll, max);
2535            }
2536
2537            return Math.min(amountToScroll, getMaxScrollAmount());
2538        } else {
2539            int indexToMakeVisible = 0;
2540            if (nextSelectedPosition != INVALID_POSITION) {
2541                indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2542            }
2543            final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2544            final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2545            int goalTop = listTop;
2546            if (positionToMakeVisible > 0) {
2547                goalTop += getArrowScrollPreviewLength();
2548            }
2549            if (viewToMakeVisible.getTop() >= goalTop) {
2550                // item is fully visible.
2551                return 0;
2552            }
2553
2554            if (nextSelectedPosition != INVALID_POSITION &&
2555                    (viewToMakeVisible.getBottom() - goalTop) >= getMaxScrollAmount()) {
2556                // item already has enough of it visible, changing selection is good enough
2557                return 0;
2558            }
2559
2560            int amountToScroll = (goalTop - viewToMakeVisible.getTop());
2561            if (mFirstPosition == 0) {
2562                // first is first in list -> make sure we don't scroll past it
2563                final int max = listTop - getChildAt(0).getTop();
2564                amountToScroll = Math.min(amountToScroll,  max);
2565            }
2566            return Math.min(amountToScroll, getMaxScrollAmount());
2567        }
2568    }
2569
2570    /**
2571     * Holds results of focus aware arrow scrolling.
2572     */
2573    static private class ArrowScrollFocusResult {
2574        private int mSelectedPosition;
2575        private int mAmountToScroll;
2576
2577        /**
2578         * How {@link android.widget.ListView#arrowScrollFocused} returns its values.
2579         */
2580        void populate(int selectedPosition, int amountToScroll) {
2581            mSelectedPosition = selectedPosition;
2582            mAmountToScroll = amountToScroll;
2583        }
2584
2585        public int getSelectedPosition() {
2586            return mSelectedPosition;
2587        }
2588
2589        public int getAmountToScroll() {
2590            return mAmountToScroll;
2591        }
2592    }
2593
2594    /**
2595     * @param direction either {@link android.view.View#FOCUS_UP} or
2596     *        {@link android.view.View#FOCUS_DOWN}.
2597     * @return The position of the next selectable position of the views that
2598     *         are currently visible, taking into account the fact that there might
2599     *         be no selection.  Returns {@link #INVALID_POSITION} if there is no
2600     *         selectable view on screen in the given direction.
2601     */
2602    private int lookForSelectablePositionOnScreen(int direction) {
2603        final int firstPosition = mFirstPosition;
2604        if (direction == View.FOCUS_DOWN) {
2605            int startPos = (mSelectedPosition != INVALID_POSITION) ?
2606                    mSelectedPosition + 1 :
2607                    firstPosition;
2608            if (startPos >= mAdapter.getCount()) {
2609                return INVALID_POSITION;
2610            }
2611            if (startPos < firstPosition) {
2612                startPos = firstPosition;
2613            }
2614
2615            final int lastVisiblePos = getLastVisiblePosition();
2616            final ListAdapter adapter = getAdapter();
2617            for (int pos = startPos; pos <= lastVisiblePos; pos++) {
2618                if (adapter.isEnabled(pos)
2619                        && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2620                    return pos;
2621                }
2622            }
2623        } else {
2624            int last = firstPosition + getChildCount() - 1;
2625            int startPos = (mSelectedPosition != INVALID_POSITION) ?
2626                    mSelectedPosition - 1 :
2627                    firstPosition + getChildCount() - 1;
2628            if (startPos < 0) {
2629                return INVALID_POSITION;
2630            }
2631            if (startPos > last) {
2632                startPos = last;
2633            }
2634
2635            final ListAdapter adapter = getAdapter();
2636            for (int pos = startPos; pos >= firstPosition; pos--) {
2637                if (adapter.isEnabled(pos)
2638                        && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2639                    return pos;
2640                }
2641            }
2642        }
2643        return INVALID_POSITION;
2644    }
2645
2646    /**
2647     * Do an arrow scroll based on focus searching.  If a new view is
2648     * given focus, return the selection delta and amount to scroll via
2649     * an {@link ArrowScrollFocusResult}, otherwise, return null.
2650     *
2651     * @param direction either {@link android.view.View#FOCUS_UP} or
2652     *        {@link android.view.View#FOCUS_DOWN}.
2653     * @return The result if focus has changed, or <code>null</code>.
2654     */
2655    private ArrowScrollFocusResult arrowScrollFocused(final int direction) {
2656        final View selectedView = getSelectedView();
2657        View newFocus;
2658        if (selectedView != null && selectedView.hasFocus()) {
2659            View oldFocus = selectedView.findFocus();
2660            newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction);
2661        } else {
2662            if (direction == View.FOCUS_DOWN) {
2663                final boolean topFadingEdgeShowing = (mFirstPosition > 0);
2664                final int listTop = mListPadding.top +
2665                        (topFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2666                final int ySearchPoint =
2667                        (selectedView != null && selectedView.getTop() > listTop) ?
2668                                selectedView.getTop() :
2669                                listTop;
2670                mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2671            } else {
2672                final boolean bottomFadingEdgeShowing =
2673                        (mFirstPosition + getChildCount() - 1) < mItemCount;
2674                final int listBottom = getHeight() - mListPadding.bottom -
2675                        (bottomFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2676                final int ySearchPoint =
2677                        (selectedView != null && selectedView.getBottom() < listBottom) ?
2678                                selectedView.getBottom() :
2679                                listBottom;
2680                mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2681            }
2682            newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, mTempRect, direction);
2683        }
2684
2685        if (newFocus != null) {
2686            final int positionOfNewFocus = positionOfNewFocus(newFocus);
2687
2688            // if the focus change is in a different new position, make sure
2689            // we aren't jumping over another selectable position
2690            if (mSelectedPosition != INVALID_POSITION && positionOfNewFocus != mSelectedPosition) {
2691                final int selectablePosition = lookForSelectablePositionOnScreen(direction);
2692                if (selectablePosition != INVALID_POSITION &&
2693                        ((direction == View.FOCUS_DOWN && selectablePosition < positionOfNewFocus) ||
2694                        (direction == View.FOCUS_UP && selectablePosition > positionOfNewFocus))) {
2695                    return null;
2696                }
2697            }
2698
2699            int focusScroll = amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus);
2700
2701            final int maxScrollAmount = getMaxScrollAmount();
2702            if (focusScroll < maxScrollAmount) {
2703                // not moving too far, safe to give next view focus
2704                newFocus.requestFocus(direction);
2705                mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll);
2706                return mArrowScrollFocusResult;
2707            } else if (distanceToView(newFocus) < maxScrollAmount){
2708                // Case to consider:
2709                // too far to get entire next focusable on screen, but by going
2710                // max scroll amount, we are getting it at least partially in view,
2711                // so give it focus and scroll the max ammount.
2712                newFocus.requestFocus(direction);
2713                mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount);
2714                return mArrowScrollFocusResult;
2715            }
2716        }
2717        return null;
2718    }
2719
2720    /**
2721     * @param newFocus The view that would have focus.
2722     * @return the position that contains newFocus
2723     */
2724    private int positionOfNewFocus(View newFocus) {
2725        final int numChildren = getChildCount();
2726        for (int i = 0; i < numChildren; i++) {
2727            final View child = getChildAt(i);
2728            if (isViewAncestorOf(newFocus, child)) {
2729                return mFirstPosition + i;
2730            }
2731        }
2732        throw new IllegalArgumentException("newFocus is not a child of any of the"
2733                + " children of the list!");
2734    }
2735
2736    /**
2737     * Return true if child is an ancestor of parent, (or equal to the parent).
2738     */
2739    private boolean isViewAncestorOf(View child, View parent) {
2740        if (child == parent) {
2741            return true;
2742        }
2743
2744        final ViewParent theParent = child.getParent();
2745        return (theParent instanceof ViewGroup) && isViewAncestorOf((View) theParent, parent);
2746    }
2747
2748    /**
2749     * Determine how much we need to scroll in order to get newFocus in view.
2750     * @param direction either {@link android.view.View#FOCUS_UP} or
2751     *        {@link android.view.View#FOCUS_DOWN}.
2752     * @param newFocus The view that would take focus.
2753     * @param positionOfNewFocus The position of the list item containing newFocus
2754     * @return The amount to scroll.  Note: this is always positive!  Direction
2755     *   needs to be taken into account when actually scrolling.
2756     */
2757    private int amountToScrollToNewFocus(int direction, View newFocus, int positionOfNewFocus) {
2758        int amountToScroll = 0;
2759        newFocus.getDrawingRect(mTempRect);
2760        offsetDescendantRectToMyCoords(newFocus, mTempRect);
2761        if (direction == View.FOCUS_UP) {
2762            if (mTempRect.top < mListPadding.top) {
2763                amountToScroll = mListPadding.top - mTempRect.top;
2764                if (positionOfNewFocus > 0) {
2765                    amountToScroll += getArrowScrollPreviewLength();
2766                }
2767            }
2768        } else {
2769            final int listBottom = getHeight() - mListPadding.bottom;
2770            if (mTempRect.bottom > listBottom) {
2771                amountToScroll = mTempRect.bottom - listBottom;
2772                if (positionOfNewFocus < mItemCount - 1) {
2773                    amountToScroll += getArrowScrollPreviewLength();
2774                }
2775            }
2776        }
2777        return amountToScroll;
2778    }
2779
2780    /**
2781     * Determine the distance to the nearest edge of a view in a particular
2782     * direction.
2783     *
2784     * @param descendant A descendant of this list.
2785     * @return The distance, or 0 if the nearest edge is already on screen.
2786     */
2787    private int distanceToView(View descendant) {
2788        int distance = 0;
2789        descendant.getDrawingRect(mTempRect);
2790        offsetDescendantRectToMyCoords(descendant, mTempRect);
2791        final int listBottom = mBottom - mTop - mListPadding.bottom;
2792        if (mTempRect.bottom < mListPadding.top) {
2793            distance = mListPadding.top - mTempRect.bottom;
2794        } else if (mTempRect.top > listBottom) {
2795            distance = mTempRect.top - listBottom;
2796        }
2797        return distance;
2798    }
2799
2800
2801    /**
2802     * Scroll the children by amount, adding a view at the end and removing
2803     * views that fall off as necessary.
2804     *
2805     * @param amount The amount (positive or negative) to scroll.
2806     */
2807    private void scrollListItemsBy(int amount) {
2808        offsetChildrenTopAndBottom(amount);
2809
2810        final int listBottom = getHeight() - mListPadding.bottom;
2811        final int listTop = mListPadding.top;
2812        final AbsListView.RecycleBin recycleBin = mRecycler;
2813
2814        if (amount < 0) {
2815            // shifted items up
2816
2817            // may need to pan views into the bottom space
2818            int numChildren = getChildCount();
2819            View last = getChildAt(numChildren - 1);
2820            while (last.getBottom() < listBottom) {
2821                final int lastVisiblePosition = mFirstPosition + numChildren - 1;
2822                if (lastVisiblePosition < mItemCount - 1) {
2823                    last = addViewBelow(last, lastVisiblePosition);
2824                    numChildren++;
2825                } else {
2826                    break;
2827                }
2828            }
2829
2830            // may have brought in the last child of the list that is skinnier
2831            // than the fading edge, thereby leaving space at the end.  need
2832            // to shift back
2833            if (last.getBottom() < listBottom) {
2834                offsetChildrenTopAndBottom(listBottom - last.getBottom());
2835            }
2836
2837            // top views may be panned off screen
2838            View first = getChildAt(0);
2839            while (first.getBottom() < listTop) {
2840                AbsListView.LayoutParams layoutParams = (LayoutParams) first.getLayoutParams();
2841                if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
2842                    detachViewFromParent(first);
2843                    recycleBin.addScrapView(first);
2844                } else {
2845                    removeViewInLayout(first);
2846                }
2847                first = getChildAt(0);
2848                mFirstPosition++;
2849            }
2850        } else {
2851            // shifted items down
2852            View first = getChildAt(0);
2853
2854            // may need to pan views into top
2855            while ((first.getTop() > listTop) && (mFirstPosition > 0)) {
2856                first = addViewAbove(first, mFirstPosition);
2857                mFirstPosition--;
2858            }
2859
2860            // may have brought the very first child of the list in too far and
2861            // need to shift it back
2862            if (first.getTop() > listTop) {
2863                offsetChildrenTopAndBottom(listTop - first.getTop());
2864            }
2865
2866            int lastIndex = getChildCount() - 1;
2867            View last = getChildAt(lastIndex);
2868
2869            // bottom view may be panned off screen
2870            while (last.getTop() > listBottom) {
2871                AbsListView.LayoutParams layoutParams = (LayoutParams) last.getLayoutParams();
2872                if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
2873                    detachViewFromParent(last);
2874                    recycleBin.addScrapView(last);
2875                } else {
2876                    removeViewInLayout(last);
2877                }
2878                last = getChildAt(--lastIndex);
2879            }
2880        }
2881    }
2882
2883    private View addViewAbove(View theView, int position) {
2884        int abovePosition = position - 1;
2885        View view = obtainView(abovePosition, mIsScrap);
2886        int edgeOfNewChild = theView.getTop() - mDividerHeight;
2887        setupChild(view, abovePosition, edgeOfNewChild, false, mListPadding.left,
2888                false, mIsScrap[0]);
2889        return view;
2890    }
2891
2892    private View addViewBelow(View theView, int position) {
2893        int belowPosition = position + 1;
2894        View view = obtainView(belowPosition, mIsScrap);
2895        int edgeOfNewChild = theView.getBottom() + mDividerHeight;
2896        setupChild(view, belowPosition, edgeOfNewChild, true, mListPadding.left,
2897                false, mIsScrap[0]);
2898        return view;
2899    }
2900
2901    /**
2902     * Indicates that the views created by the ListAdapter can contain focusable
2903     * items.
2904     *
2905     * @param itemsCanFocus true if items can get focus, false otherwise
2906     */
2907    public void setItemsCanFocus(boolean itemsCanFocus) {
2908        mItemsCanFocus = itemsCanFocus;
2909        if (!itemsCanFocus) {
2910            setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
2911        }
2912    }
2913
2914    /**
2915     * @return Whether the views created by the ListAdapter can contain focusable
2916     * items.
2917     */
2918    public boolean getItemsCanFocus() {
2919        return mItemsCanFocus;
2920    }
2921
2922    /**
2923     * @hide Pending API council approval.
2924     */
2925    @Override
2926    public boolean isOpaque() {
2927        return (mCachingStarted && mIsCacheColorOpaque && mDividerIsOpaque &&
2928                hasOpaqueScrollbars()) || super.isOpaque();
2929    }
2930
2931    @Override
2932    public void setCacheColorHint(int color) {
2933        final boolean opaque = (color >>> 24) == 0xFF;
2934        mIsCacheColorOpaque = opaque;
2935        if (opaque) {
2936            if (mDividerPaint == null) {
2937                mDividerPaint = new Paint();
2938            }
2939            mDividerPaint.setColor(color);
2940        }
2941        super.setCacheColorHint(color);
2942    }
2943
2944    @Override
2945    protected void dispatchDraw(Canvas canvas) {
2946        // Draw the dividers
2947        final int dividerHeight = mDividerHeight;
2948        final boolean drawDividers = dividerHeight > 0 && mDivider != null;
2949
2950        if (drawDividers) {
2951            // Only modify the top and bottom in the loop, we set the left and right here
2952            final Rect bounds = mTempRect;
2953            bounds.left = mPaddingLeft;
2954            bounds.right = mRight - mLeft - mPaddingRight;
2955
2956            final int count = getChildCount();
2957            final int headerCount = mHeaderViewInfos.size();
2958            final int itemCount = mItemCount;
2959            final int footerLimit = itemCount - mFooterViewInfos.size() - 1;
2960            final boolean headerDividers = mHeaderDividersEnabled;
2961            final boolean footerDividers = mFooterDividersEnabled;
2962            final int first = mFirstPosition;
2963            final boolean areAllItemsSelectable = mAreAllItemsSelectable;
2964            final ListAdapter adapter = mAdapter;
2965            // If the list is opaque *and* the background is not, we want to
2966            // fill a rect where the dividers would be for non-selectable items
2967            // If the list is opaque and the background is also opaque, we don't
2968            // need to draw anything since the background will do it for us
2969            final boolean fillForMissingDividers = isOpaque() && !super.isOpaque();
2970
2971            if (fillForMissingDividers && mDividerPaint == null && mIsCacheColorOpaque) {
2972                mDividerPaint = new Paint();
2973                mDividerPaint.setColor(getCacheColorHint());
2974            }
2975            final Paint paint = mDividerPaint;
2976
2977            final int listBottom = mBottom - mTop - mListPadding.bottom + mScrollY;
2978            if (!mStackFromBottom) {
2979                int bottom;
2980
2981                final int scrollY = mScrollY;
2982                for (int i = 0; i < count; i++) {
2983                    if ((headerDividers || first + i >= headerCount) &&
2984                            (footerDividers || first + i < footerLimit)) {
2985                        View child = getChildAt(i);
2986                        bottom = child.getBottom();
2987                        // Don't draw dividers next to items that are not enabled
2988                        if ((areAllItemsSelectable ||
2989                                (adapter.isEnabled(first + i) && (i == count - 1 ||
2990                                        adapter.isEnabled(first + i + 1))))) {
2991                            bounds.top = bottom;
2992                            bounds.bottom = bottom + dividerHeight;
2993                            drawDivider(canvas, bounds, i);
2994                        } else if (fillForMissingDividers) {
2995                            bounds.top = bottom;
2996                            bounds.bottom = bottom + dividerHeight;
2997                            canvas.drawRect(bounds, paint);
2998                        }
2999                    }
3000                }
3001            } else {
3002                int top;
3003                int listTop = mListPadding.top;
3004
3005                final int scrollY = mScrollY;
3006
3007                for (int i = 0; i < count; i++) {
3008                    if ((headerDividers || first + i >= headerCount) &&
3009                            (footerDividers || first + i < footerLimit)) {
3010                        View child = getChildAt(i);
3011                        top = child.getTop();
3012                        // Don't draw dividers next to items that are not enabled
3013                        if (top > listTop) {
3014                            if ((areAllItemsSelectable ||
3015                                    (adapter.isEnabled(first + i) && (i == count - 1 ||
3016                                            adapter.isEnabled(first + i + 1))))) {
3017                                bounds.top = top - dividerHeight;
3018                                bounds.bottom = top;
3019                                // Give the method the child ABOVE the divider, so we
3020                                // subtract one from our child
3021                                // position. Give -1 when there is no child above the
3022                                // divider.
3023                                drawDivider(canvas, bounds, i - 1);
3024                            } else if (fillForMissingDividers) {
3025                                bounds.top = top - dividerHeight;
3026                                bounds.bottom = top;
3027                                canvas.drawRect(bounds, paint);
3028                            }
3029                        }
3030                    }
3031                }
3032
3033                if (count > 0 && scrollY > 0) {
3034                    bounds.top = listBottom;
3035                    bounds.bottom = listBottom + dividerHeight;
3036                    drawDivider(canvas, bounds, -1);
3037                }
3038            }
3039        }
3040
3041        // Draw the indicators (these should be drawn above the dividers) and children
3042        super.dispatchDraw(canvas);
3043    }
3044
3045    /**
3046     * Draws a divider for the given child in the given bounds.
3047     *
3048     * @param canvas The canvas to draw to.
3049     * @param bounds The bounds of the divider.
3050     * @param childIndex The index of child (of the View) above the divider.
3051     *            This will be -1 if there is no child above the divider to be
3052     *            drawn.
3053     */
3054    void drawDivider(Canvas canvas, Rect bounds, int childIndex) {
3055        // This widget draws the same divider for all children
3056        final Drawable divider = mDivider;
3057        final boolean clipDivider = mClipDivider;
3058
3059        if (!clipDivider) {
3060            divider.setBounds(bounds);
3061        } else {
3062            canvas.save();
3063            canvas.clipRect(bounds);
3064        }
3065
3066        divider.draw(canvas);
3067
3068        if (clipDivider) {
3069            canvas.restore();
3070        }
3071    }
3072
3073    /**
3074     * Returns the drawable that will be drawn between each item in the list.
3075     *
3076     * @return the current drawable drawn between list elements
3077     */
3078    public Drawable getDivider() {
3079        return mDivider;
3080    }
3081
3082    /**
3083     * Sets the drawable that will be drawn between each item in the list. If the drawable does
3084     * not have an intrinsic height, you should also call {@link #setDividerHeight(int)}
3085     *
3086     * @param divider The drawable to use.
3087     */
3088    public void setDivider(Drawable divider) {
3089        if (divider != null) {
3090            mDividerHeight = divider.getIntrinsicHeight();
3091            mClipDivider = divider instanceof ColorDrawable;
3092        } else {
3093            mDividerHeight = 0;
3094            mClipDivider = false;
3095        }
3096        mDivider = divider;
3097        mDividerIsOpaque = divider == null || divider.getOpacity() == PixelFormat.OPAQUE;
3098        requestLayoutIfNecessary();
3099    }
3100
3101    /**
3102     * @return Returns the height of the divider that will be drawn between each item in the list.
3103     */
3104    public int getDividerHeight() {
3105        return mDividerHeight;
3106    }
3107
3108    /**
3109     * Sets the height of the divider that will be drawn between each item in the list. Calling
3110     * this will override the intrinsic height as set by {@link #setDivider(Drawable)}
3111     *
3112     * @param height The new height of the divider in pixels.
3113     */
3114    public void setDividerHeight(int height) {
3115        mDividerHeight = height;
3116        requestLayoutIfNecessary();
3117    }
3118
3119    /**
3120     * Enables or disables the drawing of the divider for header views.
3121     *
3122     * @param headerDividersEnabled True to draw the headers, false otherwise.
3123     *
3124     * @see #setFooterDividersEnabled(boolean)
3125     * @see #addHeaderView(android.view.View)
3126     */
3127    public void setHeaderDividersEnabled(boolean headerDividersEnabled) {
3128        mHeaderDividersEnabled = headerDividersEnabled;
3129        invalidate();
3130    }
3131
3132    /**
3133     * Enables or disables the drawing of the divider for footer views.
3134     *
3135     * @param footerDividersEnabled True to draw the footers, false otherwise.
3136     *
3137     * @see #setHeaderDividersEnabled(boolean)
3138     * @see #addFooterView(android.view.View)
3139     */
3140    public void setFooterDividersEnabled(boolean footerDividersEnabled) {
3141        mFooterDividersEnabled = footerDividersEnabled;
3142        invalidate();
3143    }
3144
3145    @Override
3146    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3147        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
3148
3149        int closetChildIndex = -1;
3150        if (gainFocus && previouslyFocusedRect != null) {
3151            previouslyFocusedRect.offset(mScrollX, mScrollY);
3152
3153            final ListAdapter adapter = mAdapter;
3154            // Don't cache the result of getChildCount or mFirstPosition here,
3155            // it could change in layoutChildren.
3156            if (adapter.getCount() < getChildCount() + mFirstPosition) {
3157                mLayoutMode = LAYOUT_NORMAL;
3158                layoutChildren();
3159            }
3160
3161            // figure out which item should be selected based on previously
3162            // focused rect
3163            Rect otherRect = mTempRect;
3164            int minDistance = Integer.MAX_VALUE;
3165            final int childCount = getChildCount();
3166            final int firstPosition = mFirstPosition;
3167
3168            for (int i = 0; i < childCount; i++) {
3169                // only consider selectable views
3170                if (!adapter.isEnabled(firstPosition + i)) {
3171                    continue;
3172                }
3173
3174                View other = getChildAt(i);
3175                other.getDrawingRect(otherRect);
3176                offsetDescendantRectToMyCoords(other, otherRect);
3177                int distance = getDistance(previouslyFocusedRect, otherRect, direction);
3178
3179                if (distance < minDistance) {
3180                    minDistance = distance;
3181                    closetChildIndex = i;
3182                }
3183            }
3184        }
3185
3186        if (closetChildIndex >= 0) {
3187            setSelection(closetChildIndex + mFirstPosition);
3188        } else {
3189            requestLayout();
3190        }
3191    }
3192
3193
3194    /*
3195     * (non-Javadoc)
3196     *
3197     * Children specified in XML are assumed to be header views. After we have
3198     * parsed them move them out of the children list and into mHeaderViews.
3199     */
3200    @Override
3201    protected void onFinishInflate() {
3202        super.onFinishInflate();
3203
3204        int count = getChildCount();
3205        if (count > 0) {
3206            for (int i = 0; i < count; ++i) {
3207                addHeaderView(getChildAt(i));
3208            }
3209            removeAllViews();
3210        }
3211    }
3212
3213    /* (non-Javadoc)
3214     * @see android.view.View#findViewById(int)
3215     * First look in our children, then in any header and footer views that may be scrolled off.
3216     */
3217    @Override
3218    protected View findViewTraversal(int id) {
3219        View v;
3220        v = super.findViewTraversal(id);
3221        if (v == null) {
3222            v = findViewInHeadersOrFooters(mHeaderViewInfos, id);
3223            if (v != null) {
3224                return v;
3225            }
3226            v = findViewInHeadersOrFooters(mFooterViewInfos, id);
3227            if (v != null) {
3228                return v;
3229            }
3230        }
3231        return v;
3232    }
3233
3234    /* (non-Javadoc)
3235     *
3236     * Look in the passed in list of headers or footers for the view.
3237     */
3238    View findViewInHeadersOrFooters(ArrayList<FixedViewInfo> where, int id) {
3239        if (where != null) {
3240            int len = where.size();
3241            View v;
3242
3243            for (int i = 0; i < len; i++) {
3244                v = where.get(i).view;
3245
3246                if (!v.isRootNamespace()) {
3247                    v = v.findViewById(id);
3248
3249                    if (v != null) {
3250                        return v;
3251                    }
3252                }
3253            }
3254        }
3255        return null;
3256    }
3257
3258    /* (non-Javadoc)
3259     * @see android.view.View#findViewWithTag(String)
3260     * First look in our children, then in any header and footer views that may be scrolled off.
3261     */
3262    @Override
3263    protected View findViewWithTagTraversal(Object tag) {
3264        View v;
3265        v = super.findViewWithTagTraversal(tag);
3266        if (v == null) {
3267            v = findViewTagInHeadersOrFooters(mHeaderViewInfos, tag);
3268            if (v != null) {
3269                return v;
3270            }
3271
3272            v = findViewTagInHeadersOrFooters(mFooterViewInfos, tag);
3273            if (v != null) {
3274                return v;
3275            }
3276        }
3277        return v;
3278    }
3279
3280    /* (non-Javadoc)
3281     *
3282     * Look in the passed in list of headers or footers for the view with the tag.
3283     */
3284    View findViewTagInHeadersOrFooters(ArrayList<FixedViewInfo> where, Object tag) {
3285        if (where != null) {
3286            int len = where.size();
3287            View v;
3288
3289            for (int i = 0; i < len; i++) {
3290                v = where.get(i).view;
3291
3292                if (!v.isRootNamespace()) {
3293                    v = v.findViewWithTag(tag);
3294
3295                    if (v != null) {
3296                        return v;
3297                    }
3298                }
3299            }
3300        }
3301        return null;
3302    }
3303
3304    @Override
3305    public boolean onTouchEvent(MotionEvent ev) {
3306        if (mItemsCanFocus && ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
3307            // Don't handle edge touches immediately -- they may actually belong to one of our
3308            // descendants.
3309            return false;
3310        }
3311        return super.onTouchEvent(ev);
3312    }
3313
3314    /**
3315     * Returns the set of checked items ids. The result is only valid if the
3316     * choice mode has not been set to {@link #CHOICE_MODE_NONE}.
3317     *
3318     * @return A new array which contains the id of each checked item in the
3319     *         list.
3320     *
3321     * @deprecated Use {@link #getCheckedItemIds()} instead.
3322     */
3323    @Deprecated
3324    public long[] getCheckItemIds() {
3325        // Use new behavior that correctly handles stable ID mapping.
3326        if (mAdapter != null && mAdapter.hasStableIds()) {
3327            return getCheckedItemIds();
3328        }
3329
3330        // Old behavior was buggy, but would sort of work for adapters without stable IDs.
3331        // Fall back to it to support legacy apps.
3332        if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null && mAdapter != null) {
3333            final SparseBooleanArray states = mCheckStates;
3334            final int count = states.size();
3335            final long[] ids = new long[count];
3336            final ListAdapter adapter = mAdapter;
3337
3338            int checkedCount = 0;
3339            for (int i = 0; i < count; i++) {
3340                if (states.valueAt(i)) {
3341                    ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
3342                }
3343            }
3344
3345            // Trim array if needed. mCheckStates may contain false values
3346            // resulting in checkedCount being smaller than count.
3347            if (checkedCount == count) {
3348                return ids;
3349            } else {
3350                final long[] result = new long[checkedCount];
3351                System.arraycopy(ids, 0, result, 0, checkedCount);
3352
3353                return result;
3354            }
3355        }
3356        return new long[0];
3357    }
3358}
3359