blob: a79c8e891c9addebe422fb6eae5fc1db6da3504d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Alan Viverette23f44322015-04-06 16:04:56 -070019import android.os.Bundle;
Romain Guy5fade8c2013-07-10 16:36:18 -070020import android.os.Trace;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080021import com.android.internal.R;
Jeff Brown4e6319b2010-12-13 10:36:51 -080022import com.android.internal.util.Predicate;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080023import com.google.android.collect.Lists;
24
Tor Norbye7b9c9122013-05-30 16:48:33 -070025import android.annotation.IdRes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.Context;
Winson Chung499cb9f2010-07-16 11:18:17 -070027import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.res.TypedArray;
29import android.graphics.Canvas;
Romain Guy8f1344f52009-05-15 16:03:59 -070030import android.graphics.Paint;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080031import android.graphics.PixelFormat;
32import android.graphics.Rect;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080033import android.graphics.drawable.Drawable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.util.AttributeSet;
alanv30ee76c2012-09-07 10:31:16 -070035import android.util.MathUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.util.SparseBooleanArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.view.FocusFinder;
38import android.view.KeyEvent;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080039import android.view.SoundEffectConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.view.View;
41import android.view.ViewDebug;
42import android.view.ViewGroup;
43import android.view.ViewParent;
Alan Viverette3e141622014-02-18 17:05:13 -080044import android.view.ViewRootImpl;
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -080045import android.view.accessibility.AccessibilityNodeInfo;
Alan Viverette23f44322015-04-06 16:04:56 -070046import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
Alan Viverette5b2081d2013-08-28 10:43:07 -070047import android.view.accessibility.AccessibilityNodeInfo.CollectionInfo;
48import android.view.accessibility.AccessibilityNodeInfo.CollectionItemInfo;
Alan Viverette3e141622014-02-18 17:05:13 -080049import android.view.accessibility.AccessibilityNodeProvider;
Winson Chung499cb9f2010-07-16 11:18:17 -070050import android.widget.RemoteViews.RemoteView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import java.util.ArrayList;
53
54/*
55 * Implementation Notes:
56 *
57 * Some terminology:
58 *
59 * index - index of the items that are currently visible
60 * position - index of the items in the cursor
61 */
62
63
64/**
65 * A view that shows items in a vertically scrolling list. The items
66 * come from the {@link ListAdapter} associated with this view.
67 *
Scott Main4c359b72012-07-24 15:51:27 -070068 * <p>See the <a href="{@docRoot}guide/topics/ui/layout/listview.html">List View</a>
69 * guide.</p>
Scott Main41ec6532010-08-19 16:57:07 -070070 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 * @attr ref android.R.styleable#ListView_entries
72 * @attr ref android.R.styleable#ListView_divider
73 * @attr ref android.R.styleable#ListView_dividerHeight
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 * @attr ref android.R.styleable#ListView_headerDividersEnabled
75 * @attr ref android.R.styleable#ListView_footerDividersEnabled
76 */
Winson Chung499cb9f2010-07-16 11:18:17 -070077@RemoteView
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078public class ListView extends AbsListView {
79 /**
80 * Used to indicate a no preference for a position type.
81 */
82 static final int NO_POSITION = -1;
83
84 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 * When arrow scrolling, ListView will never scroll more than this factor
86 * times the height of the list.
87 */
88 private static final float MAX_SCROLL_FACTOR = 0.33f;
89
90 /**
91 * When arrow scrolling, need a certain amount of pixels to preview next
92 * items. This is usually the fading edge, but if that is small enough,
93 * we want to make sure we preview at least this many pixels.
94 */
95 private static final int MIN_SCROLL_PREVIEW_PIXELS = 2;
96
97 /**
98 * A class that represents a fixed view in a list, for example a header at the top
99 * or a footer at the bottom.
100 */
101 public class FixedViewInfo {
102 /** The view to add to the list */
103 public View view;
104 /** The data backing the view. This is returned from {@link ListAdapter#getItem(int)}. */
105 public Object data;
106 /** <code>true</code> if the fixed view should be selectable in the list */
107 public boolean isSelectable;
108 }
109
110 private ArrayList<FixedViewInfo> mHeaderViewInfos = Lists.newArrayList();
111 private ArrayList<FixedViewInfo> mFooterViewInfos = Lists.newArrayList();
112
113 Drawable mDivider;
114 int mDividerHeight;
Adam Cohenfb603862010-12-17 12:03:17 -0800115
Adam Powell637d3372010-08-25 14:37:03 -0700116 Drawable mOverScrollHeader;
117 Drawable mOverScrollFooter;
118
Romain Guy24443ea2009-05-11 11:56:30 -0700119 private boolean mIsCacheColorOpaque;
120 private boolean mDividerIsOpaque;
Romain Guy24443ea2009-05-11 11:56:30 -0700121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private boolean mHeaderDividersEnabled;
123 private boolean mFooterDividersEnabled;
124
125 private boolean mAreAllItemsSelectable = true;
126
127 private boolean mItemsCanFocus = false;
128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 // used for temporary calculations.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700130 private final Rect mTempRect = new Rect();
Romain Guya02903f2009-05-23 13:26:46 -0700131 private Paint mDividerPaint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
133 // the single allocated result per list view; kinda cheesey but avoids
134 // allocating these thingies too often.
Romain Guy9c3184cc2010-02-25 17:32:54 -0800135 private final ArrowScrollFocusResult mArrowScrollFocusResult = new ArrowScrollFocusResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
Adam Powell9bf3c122010-02-26 11:32:07 -0800137 // Keeps focused children visible through resizes
138 private FocusSelector mFocusSelector;
Adam Powell8350f7d2010-07-28 14:27:28 -0700139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 public ListView(Context context) {
141 this(context, null);
142 }
143
144 public ListView(Context context, AttributeSet attrs) {
145 this(context, attrs, com.android.internal.R.attr.listViewStyle);
146 }
147
Alan Viverette617feb92013-09-09 18:09:13 -0700148 public ListView(Context context, AttributeSet attrs, int defStyleAttr) {
149 this(context, attrs, defStyleAttr, 0);
150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Alan Viverette617feb92013-09-09 18:09:13 -0700152 public ListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
153 super(context, attrs, defStyleAttr, defStyleRes);
154
155 final TypedArray a = context.obtainStyledAttributes(
156 attrs, com.android.internal.R.styleable.ListView, defStyleAttr, defStyleRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
158 CharSequence[] entries = a.getTextArray(
159 com.android.internal.R.styleable.ListView_entries);
160 if (entries != null) {
161 setAdapter(new ArrayAdapter<CharSequence>(context,
162 com.android.internal.R.layout.simple_list_item_1, entries));
163 }
164
165 final Drawable d = a.getDrawable(com.android.internal.R.styleable.ListView_divider);
166 if (d != null) {
167 // If a divider is specified use its intrinsic height for divider height
168 setDivider(d);
169 }
Adam Powellbfb5d4b2010-03-10 18:55:25 -0800170
Adam Powell637d3372010-08-25 14:37:03 -0700171 final Drawable osHeader = a.getDrawable(
172 com.android.internal.R.styleable.ListView_overScrollHeader);
173 if (osHeader != null) {
174 setOverscrollHeader(osHeader);
175 }
176
177 final Drawable osFooter = a.getDrawable(
178 com.android.internal.R.styleable.ListView_overScrollFooter);
179 if (osFooter != null) {
180 setOverscrollFooter(osFooter);
181 }
182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 // Use the height specified, zero being the default
184 final int dividerHeight = a.getDimensionPixelSize(
185 com.android.internal.R.styleable.ListView_dividerHeight, 0);
186 if (dividerHeight != 0) {
187 setDividerHeight(dividerHeight);
188 }
189
190 mHeaderDividersEnabled = a.getBoolean(R.styleable.ListView_headerDividersEnabled, true);
191 mFooterDividersEnabled = a.getBoolean(R.styleable.ListView_footerDividersEnabled, true);
192
193 a.recycle();
194 }
195
196 /**
197 * @return The maximum amount a list view will scroll in response to
198 * an arrow event.
199 */
200 public int getMaxScrollAmount() {
201 return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop));
202 }
203
204 /**
205 * Make sure views are touching the top or bottom edge, as appropriate for
206 * our gravity
207 */
208 private void adjustViewsUpOrDown() {
209 final int childCount = getChildCount();
210 int delta;
211
212 if (childCount > 0) {
213 View child;
214
215 if (!mStackFromBottom) {
216 // Uh-oh -- we came up short. Slide all views up to make them
217 // align with the top
218 child = getChildAt(0);
219 delta = child.getTop() - mListPadding.top;
220 if (mFirstPosition != 0) {
221 // It's OK to have some space above the first item if it is
222 // part of the vertical spacing
223 delta -= mDividerHeight;
224 }
225 if (delta < 0) {
226 // We only are looking to see if we are too low, not too high
227 delta = 0;
228 }
229 } else {
230 // we are too high, slide all views down to align with bottom
231 child = getChildAt(childCount - 1);
232 delta = child.getBottom() - (getHeight() - mListPadding.bottom);
233
234 if (mFirstPosition + childCount < mItemCount) {
235 // It's OK to have some space below the last item if it is
236 // part of the vertical spacing
237 delta += mDividerHeight;
238 }
239
240 if (delta > 0) {
241 delta = 0;
242 }
243 }
244
245 if (delta != 0) {
246 offsetChildrenTopAndBottom(-delta);
247 }
248 }
249 }
250
251 /**
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700252 * Add a fixed view to appear at the top of the list. If this method is
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 * called more than once, the views will appear in the order they were
254 * added. Views added using this call can take focus if they want.
255 * <p>
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700256 * Note: When first introduced, this method could only be called before
257 * setting the adapter with {@link #setAdapter(ListAdapter)}. Starting with
Chet Haasee8222dd2013-09-05 07:44:18 -0700258 * {@link android.os.Build.VERSION_CODES#KITKAT}, this method may be
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700259 * called at any time. If the ListView's adapter does not extend
260 * {@link HeaderViewListAdapter}, it will be wrapped with a supporting
261 * instance of {@link WrapperListAdapter}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 *
263 * @param v The view to add.
264 * @param data Data to associate with this view
265 * @param isSelectable whether the item is selectable
266 */
267 public void addHeaderView(View v, Object data, boolean isSelectable) {
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700268 final FixedViewInfo info = new FixedViewInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 info.view = v;
270 info.data = data;
271 info.isSelectable = isSelectable;
272 mHeaderViewInfos.add(info);
Alan Viverette20cc6052013-11-15 15:56:38 -0800273 mAreAllItemsSelectable &= isSelectable;
Marco Nelissen22c04a32011-04-19 14:07:55 -0700274
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700275 // Wrap the adapter if it wasn't already wrapped.
276 if (mAdapter != null) {
277 if (!(mAdapter instanceof HeaderViewListAdapter)) {
278 mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, mAdapter);
279 }
280
281 // In the case of re-adding a header view, or adding one later on,
282 // we need to notify the observer.
283 if (mDataSetObserver != null) {
284 mDataSetObserver.onChanged();
285 }
Marco Nelissen22c04a32011-04-19 14:07:55 -0700286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 }
288
289 /**
290 * Add a fixed view to appear at the top of the list. If addHeaderView is
291 * called more than once, the views will appear in the order they were
292 * added. Views added using this call can take focus if they want.
293 * <p>
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700294 * Note: When first introduced, this method could only be called before
295 * setting the adapter with {@link #setAdapter(ListAdapter)}. Starting with
Chet Haasee8222dd2013-09-05 07:44:18 -0700296 * {@link android.os.Build.VERSION_CODES#KITKAT}, this method may be
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700297 * called at any time. If the ListView's adapter does not extend
298 * {@link HeaderViewListAdapter}, it will be wrapped with a supporting
299 * instance of {@link WrapperListAdapter}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 *
301 * @param v The view to add.
302 */
303 public void addHeaderView(View v) {
304 addHeaderView(v, null, true);
305 }
306
307 @Override
308 public int getHeaderViewsCount() {
309 return mHeaderViewInfos.size();
310 }
311
312 /**
313 * Removes a previously-added header view.
314 *
315 * @param v The view to remove
316 * @return true if the view was removed, false if the view was not a header
317 * view
318 */
319 public boolean removeHeaderView(View v) {
320 if (mHeaderViewInfos.size() > 0) {
321 boolean result = false;
Adam Powell247a0f02011-09-13 13:11:29 -0700322 if (mAdapter != null && ((HeaderViewListAdapter) mAdapter).removeHeader(v)) {
Marco Nelissen22c04a32011-04-19 14:07:55 -0700323 if (mDataSetObserver != null) {
324 mDataSetObserver.onChanged();
325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 result = true;
327 }
328 removeFixedViewInfo(v, mHeaderViewInfos);
329 return result;
330 }
331 return false;
332 }
333
334 private void removeFixedViewInfo(View v, ArrayList<FixedViewInfo> where) {
335 int len = where.size();
336 for (int i = 0; i < len; ++i) {
337 FixedViewInfo info = where.get(i);
338 if (info.view == v) {
339 where.remove(i);
340 break;
341 }
342 }
343 }
344
345 /**
346 * Add a fixed view to appear at the bottom of the list. If addFooterView is
347 * called more than once, the views will appear in the order they were
348 * added. Views added using this call can take focus if they want.
349 * <p>
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700350 * Note: When first introduced, this method could only be called before
351 * setting the adapter with {@link #setAdapter(ListAdapter)}. Starting with
Chet Haasee8222dd2013-09-05 07:44:18 -0700352 * {@link android.os.Build.VERSION_CODES#KITKAT}, this method may be
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700353 * called at any time. If the ListView's adapter does not extend
354 * {@link HeaderViewListAdapter}, it will be wrapped with a supporting
355 * instance of {@link WrapperListAdapter}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 *
357 * @param v The view to add.
358 * @param data Data to associate with this view
359 * @param isSelectable true if the footer view can be selected
360 */
361 public void addFooterView(View v, Object data, boolean isSelectable) {
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700362 final FixedViewInfo info = new FixedViewInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 info.view = v;
364 info.data = data;
365 info.isSelectable = isSelectable;
366 mFooterViewInfos.add(info);
Alan Viverette20cc6052013-11-15 15:56:38 -0800367 mAreAllItemsSelectable &= isSelectable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700369 // Wrap the adapter if it wasn't already wrapped.
370 if (mAdapter != null) {
371 if (!(mAdapter instanceof HeaderViewListAdapter)) {
372 mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, mAdapter);
373 }
374
375 // In the case of re-adding a footer view, or adding one later on,
376 // we need to notify the observer.
377 if (mDataSetObserver != null) {
378 mDataSetObserver.onChanged();
379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
381 }
382
383 /**
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700384 * Add a fixed view to appear at the bottom of the list. If addFooterView is
385 * called more than once, the views will appear in the order they were
386 * added. Views added using this call can take focus if they want.
387 * <p>
388 * Note: When first introduced, this method could only be called before
389 * setting the adapter with {@link #setAdapter(ListAdapter)}. Starting with
Chet Haasee8222dd2013-09-05 07:44:18 -0700390 * {@link android.os.Build.VERSION_CODES#KITKAT}, this method may be
Alan Viverette72e2f2a2013-06-12 12:56:29 -0700391 * called at any time. If the ListView's adapter does not extend
392 * {@link HeaderViewListAdapter}, it will be wrapped with a supporting
393 * instance of {@link WrapperListAdapter}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 *
395 * @param v The view to add.
396 */
397 public void addFooterView(View v) {
398 addFooterView(v, null, true);
399 }
400
401 @Override
402 public int getFooterViewsCount() {
403 return mFooterViewInfos.size();
404 }
405
406 /**
407 * Removes a previously-added footer view.
408 *
409 * @param v The view to remove
410 * @return
411 * true if the view was removed, false if the view was not a footer view
412 */
413 public boolean removeFooterView(View v) {
414 if (mFooterViewInfos.size() > 0) {
415 boolean result = false;
Adam Powell247a0f02011-09-13 13:11:29 -0700416 if (mAdapter != null && ((HeaderViewListAdapter) mAdapter).removeFooter(v)) {
Marco Nelissen22c04a32011-04-19 14:07:55 -0700417 if (mDataSetObserver != null) {
418 mDataSetObserver.onChanged();
419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 result = true;
421 }
422 removeFixedViewInfo(v, mFooterViewInfos);
423 return result;
424 }
425 return false;
426 }
427
428 /**
429 * Returns the adapter currently in use in this ListView. The returned adapter
430 * might not be the same adapter passed to {@link #setAdapter(ListAdapter)} but
431 * might be a {@link WrapperListAdapter}.
432 *
433 * @return The adapter currently used to display data in this ListView.
434 *
435 * @see #setAdapter(ListAdapter)
436 */
437 @Override
438 public ListAdapter getAdapter() {
439 return mAdapter;
440 }
441
442 /**
Winson Chung499cb9f2010-07-16 11:18:17 -0700443 * Sets up this AbsListView to use a remote views adapter which connects to a RemoteViewsService
444 * through the specified intent.
445 * @param intent the intent used to identify the RemoteViewsService for the adapter to connect to.
446 */
447 @android.view.RemotableViewMethod
448 public void setRemoteViewsAdapter(Intent intent) {
449 super.setRemoteViewsAdapter(intent);
450 }
451
452 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 * Sets the data behind this ListView.
454 *
455 * The adapter passed to this method may be wrapped by a {@link WrapperListAdapter},
456 * depending on the ListView features currently in use. For instance, adding
457 * headers and/or footers will cause the adapter to be wrapped.
458 *
459 * @param adapter The ListAdapter which is responsible for maintaining the
460 * data backing this list and for producing a view to represent an
461 * item in that data set.
462 *
463 * @see #getAdapter()
464 */
465 @Override
466 public void setAdapter(ListAdapter adapter) {
Romain Guydf36b052010-05-19 21:13:20 -0700467 if (mAdapter != null && mDataSetObserver != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 mAdapter.unregisterDataSetObserver(mDataSetObserver);
469 }
470
471 resetList();
472 mRecycler.clear();
473
474 if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
475 mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
476 } else {
477 mAdapter = adapter;
478 }
479
480 mOldSelectedPosition = INVALID_POSITION;
481 mOldSelectedRowId = INVALID_ROW_ID;
Adam Powellf343e1b2010-08-13 18:27:04 -0700482
483 // AbsListView#setAdapter will update choice mode states.
484 super.setAdapter(adapter);
485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 if (mAdapter != null) {
487 mAreAllItemsSelectable = mAdapter.areAllItemsEnabled();
488 mOldItemCount = mItemCount;
489 mItemCount = mAdapter.getCount();
490 checkFocus();
491
492 mDataSetObserver = new AdapterDataSetObserver();
493 mAdapter.registerDataSetObserver(mDataSetObserver);
494
495 mRecycler.setViewTypeCount(mAdapter.getViewTypeCount());
496
497 int position;
498 if (mStackFromBottom) {
499 position = lookForSelectablePosition(mItemCount - 1, false);
500 } else {
501 position = lookForSelectablePosition(0, true);
502 }
503 setSelectedPositionInt(position);
504 setNextSelectedPositionInt(position);
505
506 if (mItemCount == 0) {
507 // Nothing selected
508 checkSelectionChanged();
509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 } else {
511 mAreAllItemsSelectable = true;
512 checkFocus();
513 // Nothing selected
514 checkSelectionChanged();
515 }
516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 requestLayout();
518 }
519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 /**
521 * The list is empty. Clear everything out.
522 */
523 @Override
524 void resetList() {
Romain Guy2e447d42009-04-28 18:01:24 -0700525 // The parent's resetList() will remove all views from the layout so we need to
526 // cleanup the state of our footers and headers
527 clearRecycledState(mHeaderViewInfos);
528 clearRecycledState(mFooterViewInfos);
529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 super.resetList();
Romain Guy2e447d42009-04-28 18:01:24 -0700531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 mLayoutMode = LAYOUT_NORMAL;
533 }
534
Romain Guy2e447d42009-04-28 18:01:24 -0700535 private void clearRecycledState(ArrayList<FixedViewInfo> infos) {
536 if (infos != null) {
537 final int count = infos.size();
538
539 for (int i = 0; i < count; i++) {
540 final View child = infos.get(i).view;
541 final LayoutParams p = (LayoutParams) child.getLayoutParams();
542 if (p != null) {
543 p.recycledHeaderFooter = false;
544 }
545 }
546 }
547 }
548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 /**
550 * @return Whether the list needs to show the top fading edge
551 */
552 private boolean showingTopFadingEdge() {
553 final int listTop = mScrollY + mListPadding.top;
554 return (mFirstPosition > 0) || (getChildAt(0).getTop() > listTop);
555 }
556
557 /**
558 * @return Whether the list needs to show the bottom fading edge
559 */
560 private boolean showingBottomFadingEdge() {
561 final int childCount = getChildCount();
562 final int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
563 final int lastVisiblePosition = mFirstPosition + childCount - 1;
564
565 final int listBottom = mScrollY + getHeight() - mListPadding.bottom;
566
567 return (lastVisiblePosition < mItemCount - 1)
568 || (bottomOfBottomChild < listBottom);
569 }
570
571
572 @Override
573 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
574
575 int rectTopWithinChild = rect.top;
576
577 // offset so rect is in coordinates of the this view
578 rect.offset(child.getLeft(), child.getTop());
579 rect.offset(-child.getScrollX(), -child.getScrollY());
580
581 final int height = getHeight();
582 int listUnfadedTop = getScrollY();
583 int listUnfadedBottom = listUnfadedTop + height;
584 final int fadingEdge = getVerticalFadingEdgeLength();
585
586 if (showingTopFadingEdge()) {
587 // leave room for top fading edge as long as rect isn't at very top
588 if ((mSelectedPosition > 0) || (rectTopWithinChild > fadingEdge)) {
589 listUnfadedTop += fadingEdge;
590 }
591 }
592
593 int childCount = getChildCount();
594 int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
595
596 if (showingBottomFadingEdge()) {
597 // leave room for bottom fading edge as long as rect isn't at very bottom
598 if ((mSelectedPosition < mItemCount - 1)
599 || (rect.bottom < (bottomOfBottomChild - fadingEdge))) {
600 listUnfadedBottom -= fadingEdge;
601 }
602 }
603
604 int scrollYDelta = 0;
605
606 if (rect.bottom > listUnfadedBottom && rect.top > listUnfadedTop) {
607 // need to MOVE DOWN to get it in view: move down just enough so
608 // that the entire rectangle is in view (or at least the first
609 // screen size chunk).
610
611 if (rect.height() > height) {
612 // just enough to get screen size chunk on
613 scrollYDelta += (rect.top - listUnfadedTop);
614 } else {
615 // get entire rect at bottom of screen
616 scrollYDelta += (rect.bottom - listUnfadedBottom);
617 }
618
619 // make sure we aren't scrolling beyond the end of our children
620 int distanceToBottom = bottomOfBottomChild - listUnfadedBottom;
621 scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
622 } else if (rect.top < listUnfadedTop && rect.bottom < listUnfadedBottom) {
623 // need to MOVE UP to get it in view: move up just enough so that
624 // entire rectangle is in view (or at least the first screen
625 // size chunk of it).
626
627 if (rect.height() > height) {
628 // screen size chunk
629 scrollYDelta -= (listUnfadedBottom - rect.bottom);
630 } else {
631 // entire rect at top
632 scrollYDelta -= (listUnfadedTop - rect.top);
633 }
634
635 // make sure we aren't scrolling any further than the top our children
636 int top = getChildAt(0).getTop();
637 int deltaToTop = top - listUnfadedTop;
638 scrollYDelta = Math.max(scrollYDelta, deltaToTop);
639 }
640
641 final boolean scroll = scrollYDelta != 0;
642 if (scroll) {
643 scrollListItemsBy(-scrollYDelta);
Dianne Hackborn079e2352010-10-18 17:02:43 -0700644 positionSelector(INVALID_POSITION, child);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 mSelectedTop = child.getTop();
646 invalidate();
647 }
648 return scroll;
649 }
650
651 /**
652 * {@inheritDoc}
653 */
654 @Override
655 void fillGap(boolean down) {
656 final int count = getChildCount();
657 if (down) {
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800658 int paddingTop = 0;
659 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
660 paddingTop = getListPaddingTop();
661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 final int startOffset = count > 0 ? getChildAt(count - 1).getBottom() + mDividerHeight :
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800663 paddingTop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 fillDown(mFirstPosition + count, startOffset);
665 correctTooHigh(getChildCount());
666 } else {
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800667 int paddingBottom = 0;
668 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
669 paddingBottom = getListPaddingBottom();
670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 final int startOffset = count > 0 ? getChildAt(0).getTop() - mDividerHeight :
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800672 getHeight() - paddingBottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 fillUp(mFirstPosition - 1, startOffset);
674 correctTooLow(getChildCount());
675 }
676 }
677
678 /**
679 * Fills the list from pos down to the end of the list view.
680 *
681 * @param pos The first position to put in the list
682 *
683 * @param nextTop The location where the top of the item associated with pos
684 * should be drawn
685 *
686 * @return The view that is currently selected, if it happens to be in the
687 * range that we draw.
688 */
689 private View fillDown(int pos, int nextTop) {
690 View selectedView = null;
691
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800692 int end = (mBottom - mTop);
693 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
694 end -= mListPadding.bottom;
695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696
697 while (nextTop < end && pos < mItemCount) {
698 // is this the selected item?
699 boolean selected = pos == mSelectedPosition;
700 View child = makeAndAddView(pos, nextTop, true, mListPadding.left, selected);
701
702 nextTop = child.getBottom() + mDividerHeight;
703 if (selected) {
704 selectedView = child;
705 }
706 pos++;
707 }
708
Adam Cohenb9673922012-01-05 13:58:47 -0800709 setVisibleRangeHint(mFirstPosition, mFirstPosition + getChildCount() - 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 return selectedView;
711 }
712
713 /**
714 * Fills the list from pos up to the top of the list view.
715 *
716 * @param pos The first position to put in the list
717 *
718 * @param nextBottom The location where the bottom of the item associated
719 * with pos should be drawn
720 *
721 * @return The view that is currently selected
722 */
723 private View fillUp(int pos, int nextBottom) {
724 View selectedView = null;
725
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800726 int end = 0;
727 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
728 end = mListPadding.top;
729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730
731 while (nextBottom > end && pos >= 0) {
732 // is this the selected item?
733 boolean selected = pos == mSelectedPosition;
734 View child = makeAndAddView(pos, nextBottom, false, mListPadding.left, selected);
735 nextBottom = child.getTop() - mDividerHeight;
736 if (selected) {
737 selectedView = child;
738 }
739 pos--;
740 }
741
742 mFirstPosition = pos + 1;
Adam Cohenb9673922012-01-05 13:58:47 -0800743 setVisibleRangeHint(mFirstPosition, mFirstPosition + getChildCount() - 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 return selectedView;
745 }
746
747 /**
748 * Fills the list from top to bottom, starting with mFirstPosition
749 *
750 * @param nextTop The location where the top of the first item should be
751 * drawn
752 *
753 * @return The view that is currently selected
754 */
755 private View fillFromTop(int nextTop) {
756 mFirstPosition = Math.min(mFirstPosition, mSelectedPosition);
757 mFirstPosition = Math.min(mFirstPosition, mItemCount - 1);
758 if (mFirstPosition < 0) {
759 mFirstPosition = 0;
760 }
761 return fillDown(mFirstPosition, nextTop);
762 }
763
764
765 /**
766 * Put mSelectedPosition in the middle of the screen and then build up and
767 * down from there. This method forces mSelectedPosition to the center.
768 *
769 * @param childrenTop Top of the area in which children can be drawn, as
770 * measured in pixels
771 * @param childrenBottom Bottom of the area in which children can be drawn,
772 * as measured in pixels
773 * @return Currently selected view
774 */
775 private View fillFromMiddle(int childrenTop, int childrenBottom) {
776 int height = childrenBottom - childrenTop;
777
778 int position = reconcileSelectedPosition();
779
780 View sel = makeAndAddView(position, childrenTop, true,
781 mListPadding.left, true);
782 mFirstPosition = position;
783
784 int selHeight = sel.getMeasuredHeight();
785 if (selHeight <= height) {
786 sel.offsetTopAndBottom((height - selHeight) / 2);
787 }
788
789 fillAboveAndBelow(sel, position);
790
791 if (!mStackFromBottom) {
792 correctTooHigh(getChildCount());
793 } else {
794 correctTooLow(getChildCount());
795 }
796
797 return sel;
798 }
799
800 /**
801 * Once the selected view as been placed, fill up the visible area above and
802 * below it.
803 *
804 * @param sel The selected view
805 * @param position The position corresponding to sel
806 */
807 private void fillAboveAndBelow(View sel, int position) {
808 final int dividerHeight = mDividerHeight;
809 if (!mStackFromBottom) {
810 fillUp(position - 1, sel.getTop() - dividerHeight);
811 adjustViewsUpOrDown();
812 fillDown(position + 1, sel.getBottom() + dividerHeight);
813 } else {
814 fillDown(position + 1, sel.getBottom() + dividerHeight);
815 adjustViewsUpOrDown();
816 fillUp(position - 1, sel.getTop() - dividerHeight);
817 }
818 }
819
820
821 /**
822 * Fills the grid based on positioning the new selection at a specific
823 * location. The selection may be moved so that it does not intersect the
824 * faded edges. The grid is then filled upwards and downwards from there.
825 *
826 * @param selectedTop Where the selected item should be
827 * @param childrenTop Where to start drawing children
828 * @param childrenBottom Last pixel where children can be drawn
829 * @return The view that currently has selection
830 */
831 private View fillFromSelection(int selectedTop, int childrenTop, int childrenBottom) {
832 int fadingEdgeLength = getVerticalFadingEdgeLength();
833 final int selectedPosition = mSelectedPosition;
834
835 View sel;
836
837 final int topSelectionPixel = getTopSelectionPixel(childrenTop, fadingEdgeLength,
838 selectedPosition);
839 final int bottomSelectionPixel = getBottomSelectionPixel(childrenBottom, fadingEdgeLength,
840 selectedPosition);
841
842 sel = makeAndAddView(selectedPosition, selectedTop, true, mListPadding.left, true);
843
844
845 // Some of the newly selected item extends below the bottom of the list
846 if (sel.getBottom() > bottomSelectionPixel) {
847 // Find space available above the selection into which we can scroll
848 // upwards
849 final int spaceAbove = sel.getTop() - topSelectionPixel;
850
851 // Find space required to bring the bottom of the selected item
852 // fully into view
853 final int spaceBelow = sel.getBottom() - bottomSelectionPixel;
854 final int offset = Math.min(spaceAbove, spaceBelow);
855
856 // Now offset the selected item to get it into view
857 sel.offsetTopAndBottom(-offset);
858 } else if (sel.getTop() < topSelectionPixel) {
859 // Find space required to bring the top of the selected item fully
860 // into view
861 final int spaceAbove = topSelectionPixel - sel.getTop();
862
863 // Find space available below the selection into which we can scroll
864 // downwards
865 final int spaceBelow = bottomSelectionPixel - sel.getBottom();
866 final int offset = Math.min(spaceAbove, spaceBelow);
867
868 // Offset the selected item to get it into view
869 sel.offsetTopAndBottom(offset);
870 }
871
872 // Fill in views above and below
873 fillAboveAndBelow(sel, selectedPosition);
874
875 if (!mStackFromBottom) {
876 correctTooHigh(getChildCount());
877 } else {
878 correctTooLow(getChildCount());
879 }
880
881 return sel;
882 }
883
884 /**
885 * Calculate the bottom-most pixel we can draw the selection into
886 *
887 * @param childrenBottom Bottom pixel were children can be drawn
888 * @param fadingEdgeLength Length of the fading edge in pixels, if present
889 * @param selectedPosition The position that will be selected
890 * @return The bottom-most pixel we can draw the selection into
891 */
892 private int getBottomSelectionPixel(int childrenBottom, int fadingEdgeLength,
893 int selectedPosition) {
894 int bottomSelectionPixel = childrenBottom;
895 if (selectedPosition != mItemCount - 1) {
896 bottomSelectionPixel -= fadingEdgeLength;
897 }
898 return bottomSelectionPixel;
899 }
900
901 /**
902 * Calculate the top-most pixel we can draw the selection into
903 *
904 * @param childrenTop Top pixel were children can be drawn
905 * @param fadingEdgeLength Length of the fading edge in pixels, if present
906 * @param selectedPosition The position that will be selected
907 * @return The top-most pixel we can draw the selection into
908 */
909 private int getTopSelectionPixel(int childrenTop, int fadingEdgeLength, int selectedPosition) {
910 // first pixel we can draw the selection into
911 int topSelectionPixel = childrenTop;
912 if (selectedPosition > 0) {
913 topSelectionPixel += fadingEdgeLength;
914 }
915 return topSelectionPixel;
916 }
917
Winson Chung499cb9f2010-07-16 11:18:17 -0700918 /**
919 * Smoothly scroll to the specified adapter position. The view will
920 * scroll such that the indicated position is displayed.
921 * @param position Scroll to this adapter position.
922 */
923 @android.view.RemotableViewMethod
924 public void smoothScrollToPosition(int position) {
925 super.smoothScrollToPosition(position);
926 }
927
928 /**
929 * Smoothly scroll to the specified adapter position offset. The view will
930 * scroll such that the indicated position is displayed.
931 * @param offset The amount to offset from the adapter position to scroll to.
932 */
933 @android.view.RemotableViewMethod
934 public void smoothScrollByOffset(int offset) {
935 super.smoothScrollByOffset(offset);
936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937
938 /**
939 * Fills the list based on positioning the new selection relative to the old
940 * selection. The new selection will be placed at, above, or below the
941 * location of the new selection depending on how the selection is moving.
942 * The selection will then be pinned to the visible part of the screen,
943 * excluding the edges that are faded. The list is then filled upwards and
944 * downwards from there.
945 *
946 * @param oldSel The old selected view. Useful for trying to put the new
947 * selection in the same place
948 * @param newSel The view that is to become selected. Useful for trying to
949 * put the new selection in the same place
950 * @param delta Which way we are moving
951 * @param childrenTop Where to start drawing children
952 * @param childrenBottom Last pixel where children can be drawn
953 * @return The view that currently has selection
954 */
955 private View moveSelection(View oldSel, View newSel, int delta, int childrenTop,
956 int childrenBottom) {
957 int fadingEdgeLength = getVerticalFadingEdgeLength();
958 final int selectedPosition = mSelectedPosition;
959
960 View sel;
961
962 final int topSelectionPixel = getTopSelectionPixel(childrenTop, fadingEdgeLength,
963 selectedPosition);
964 final int bottomSelectionPixel = getBottomSelectionPixel(childrenTop, fadingEdgeLength,
965 selectedPosition);
966
967 if (delta > 0) {
968 /*
969 * Case 1: Scrolling down.
970 */
971
972 /*
973 * Before After
974 * | | | |
975 * +-------+ +-------+
976 * | A | | A |
977 * | 1 | => +-------+
978 * +-------+ | B |
979 * | B | | 2 |
980 * +-------+ +-------+
981 * | | | |
982 *
983 * Try to keep the top of the previously selected item where it was.
984 * oldSel = A
985 * sel = B
986 */
987
988 // Put oldSel (A) where it belongs
989 oldSel = makeAndAddView(selectedPosition - 1, oldSel.getTop(), true,
990 mListPadding.left, false);
991
992 final int dividerHeight = mDividerHeight;
993
994 // Now put the new selection (B) below that
995 sel = makeAndAddView(selectedPosition, oldSel.getBottom() + dividerHeight, true,
996 mListPadding.left, true);
997
998 // Some of the newly selected item extends below the bottom of the list
999 if (sel.getBottom() > bottomSelectionPixel) {
1000
1001 // Find space available above the selection into which we can scroll upwards
1002 int spaceAbove = sel.getTop() - topSelectionPixel;
1003
1004 // Find space required to bring the bottom of the selected item fully into view
1005 int spaceBelow = sel.getBottom() - bottomSelectionPixel;
1006
1007 // Don't scroll more than half the height of the list
1008 int halfVerticalSpace = (childrenBottom - childrenTop) / 2;
1009 int offset = Math.min(spaceAbove, spaceBelow);
1010 offset = Math.min(offset, halfVerticalSpace);
1011
1012 // We placed oldSel, so offset that item
1013 oldSel.offsetTopAndBottom(-offset);
1014 // Now offset the selected item to get it into view
1015 sel.offsetTopAndBottom(-offset);
1016 }
1017
1018 // Fill in views above and below
1019 if (!mStackFromBottom) {
1020 fillUp(mSelectedPosition - 2, sel.getTop() - dividerHeight);
1021 adjustViewsUpOrDown();
1022 fillDown(mSelectedPosition + 1, sel.getBottom() + dividerHeight);
1023 } else {
1024 fillDown(mSelectedPosition + 1, sel.getBottom() + dividerHeight);
1025 adjustViewsUpOrDown();
1026 fillUp(mSelectedPosition - 2, sel.getTop() - dividerHeight);
1027 }
1028 } else if (delta < 0) {
1029 /*
1030 * Case 2: Scrolling up.
1031 */
1032
1033 /*
1034 * Before After
1035 * | | | |
1036 * +-------+ +-------+
1037 * | A | | A |
1038 * +-------+ => | 1 |
1039 * | B | +-------+
1040 * | 2 | | B |
1041 * +-------+ +-------+
1042 * | | | |
1043 *
1044 * Try to keep the top of the item about to become selected where it was.
1045 * newSel = A
1046 * olSel = B
1047 */
1048
1049 if (newSel != null) {
1050 // Try to position the top of newSel (A) where it was before it was selected
1051 sel = makeAndAddView(selectedPosition, newSel.getTop(), true, mListPadding.left,
1052 true);
1053 } else {
1054 // If (A) was not on screen and so did not have a view, position
1055 // it above the oldSel (B)
1056 sel = makeAndAddView(selectedPosition, oldSel.getTop(), false, mListPadding.left,
1057 true);
1058 }
1059
1060 // Some of the newly selected item extends above the top of the list
1061 if (sel.getTop() < topSelectionPixel) {
1062 // Find space required to bring the top of the selected item fully into view
1063 int spaceAbove = topSelectionPixel - sel.getTop();
1064
1065 // Find space available below the selection into which we can scroll downwards
1066 int spaceBelow = bottomSelectionPixel - sel.getBottom();
1067
1068 // Don't scroll more than half the height of the list
1069 int halfVerticalSpace = (childrenBottom - childrenTop) / 2;
1070 int offset = Math.min(spaceAbove, spaceBelow);
1071 offset = Math.min(offset, halfVerticalSpace);
1072
1073 // Offset the selected item to get it into view
1074 sel.offsetTopAndBottom(offset);
1075 }
1076
1077 // Fill in views above and below
1078 fillAboveAndBelow(sel, selectedPosition);
1079 } else {
1080
1081 int oldTop = oldSel.getTop();
1082
1083 /*
1084 * Case 3: Staying still
1085 */
1086 sel = makeAndAddView(selectedPosition, oldTop, true, mListPadding.left, true);
1087
1088 // We're staying still...
1089 if (oldTop < childrenTop) {
1090 // ... but the top of the old selection was off screen.
1091 // (This can happen if the data changes size out from under us)
1092 int newBottom = sel.getBottom();
1093 if (newBottom < childrenTop + 20) {
1094 // Not enough visible -- bring it onscreen
1095 sel.offsetTopAndBottom(childrenTop - sel.getTop());
1096 }
1097 }
1098
1099 // Fill in views above and below
1100 fillAboveAndBelow(sel, selectedPosition);
1101 }
1102
1103 return sel;
1104 }
1105
Adam Powell9bf3c122010-02-26 11:32:07 -08001106 private class FocusSelector implements Runnable {
1107 private int mPosition;
1108 private int mPositionTop;
1109
1110 public FocusSelector setup(int position, int top) {
1111 mPosition = position;
1112 mPositionTop = top;
1113 return this;
1114 }
1115
1116 public void run() {
1117 setSelectionFromTop(mPosition, mPositionTop);
1118 }
1119 }
1120
1121 @Override
1122 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1123 if (getChildCount() > 0) {
1124 View focusedChild = getFocusedChild();
1125 if (focusedChild != null) {
1126 final int childPosition = mFirstPosition + indexOfChild(focusedChild);
1127 final int childBottom = focusedChild.getBottom();
1128 final int offset = Math.max(0, childBottom - (h - mPaddingTop));
1129 final int top = focusedChild.getTop() - offset;
1130 if (mFocusSelector == null) {
1131 mFocusSelector = new FocusSelector();
1132 }
1133 post(mFocusSelector.setup(childPosition, top));
1134 }
1135 }
1136 super.onSizeChanged(w, h, oldw, oldh);
1137 }
1138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 @Override
1140 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1141 // Sets up mListPadding
1142 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1143
1144 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
1145 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
1146 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
1147 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
1148
1149 int childWidth = 0;
1150 int childHeight = 0;
Dianne Hackborn189ee182010-12-02 21:48:53 -08001151 int childState = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152
1153 mItemCount = mAdapter == null ? 0 : mAdapter.getCount();
1154 if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED ||
1155 heightMode == MeasureSpec.UNSPECIFIED)) {
Romain Guy21875052010-01-06 18:48:08 -08001156 final View child = obtainView(0, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157
Filip Gruszczynskib6824bf2015-04-13 09:16:25 -07001158 measureScrapChild(child, 0, widthMeasureSpec, heightSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159
1160 childWidth = child.getMeasuredWidth();
1161 childHeight = child.getMeasuredHeight();
Dianne Hackborn189ee182010-12-02 21:48:53 -08001162 childState = combineMeasuredStates(childState, child.getMeasuredState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163
Romain Guy9c3184cc2010-02-25 17:32:54 -08001164 if (recycleOnMeasure() && mRecycler.shouldRecycleViewType(
1165 ((LayoutParams) child.getLayoutParams()).viewType)) {
Alan Viverette4771b552014-08-15 18:02:23 -07001166 mRecycler.addScrapView(child, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
1168 }
1169
1170 if (widthMode == MeasureSpec.UNSPECIFIED) {
1171 widthSize = mListPadding.left + mListPadding.right + childWidth +
1172 getVerticalScrollbarWidth();
Dianne Hackborn189ee182010-12-02 21:48:53 -08001173 } else {
1174 widthSize |= (childState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 }
1176
1177 if (heightMode == MeasureSpec.UNSPECIFIED) {
1178 heightSize = mListPadding.top + mListPadding.bottom + childHeight +
1179 getVerticalFadingEdgeLength() * 2;
1180 }
1181
1182 if (heightMode == MeasureSpec.AT_MOST) {
1183 // TODO: after first layout we should maybe start at the first visible position, not 0
1184 heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);
1185 }
1186
Dianne Hackborn189ee182010-12-02 21:48:53 -08001187 setMeasuredDimension(widthSize , heightSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 mWidthMeasureSpec = widthMeasureSpec;
1189 }
1190
Filip Gruszczynskib6824bf2015-04-13 09:16:25 -07001191 private void measureScrapChild(View child, int position, int widthMeasureSpec, int heightHint) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 LayoutParams p = (LayoutParams) child.getLayoutParams();
1193 if (p == null) {
Adam Powellaebd28f2012-02-22 10:31:16 -08001194 p = (AbsListView.LayoutParams) generateDefaultLayoutParams();
The Android Open Source Project4df24232009-03-05 14:34:35 -08001195 child.setLayoutParams(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 }
1197 p.viewType = mAdapter.getItemViewType(position);
Romain Guy0bf88592010-03-02 13:38:44 -08001198 p.forceAdd = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199
1200 int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec,
1201 mListPadding.left + mListPadding.right, p.width);
1202 int lpHeight = p.height;
1203 int childHeightSpec;
1204 if (lpHeight > 0) {
1205 childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
1206 } else {
Filip Gruszczynskib6824bf2015-04-13 09:16:25 -07001207 childHeightSpec = MeasureSpec.makeMeasureSpec(heightHint, MeasureSpec.UNSPECIFIED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209 child.measure(childWidthSpec, childHeightSpec);
1210 }
1211
1212 /**
1213 * @return True to recycle the views used to measure this ListView in
1214 * UNSPECIFIED/AT_MOST modes, false otherwise.
1215 * @hide
1216 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001217 @ViewDebug.ExportedProperty(category = "list")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 protected boolean recycleOnMeasure() {
1219 return true;
1220 }
1221
1222 /**
1223 * Measures the height of the given range of children (inclusive) and
1224 * returns the height with this ListView's padding and divider heights
1225 * included. If maxHeight is provided, the measuring will stop when the
1226 * current height reaches maxHeight.
1227 *
1228 * @param widthMeasureSpec The width measure spec to be given to a child's
1229 * {@link View#measure(int, int)}.
1230 * @param startPosition The position of the first child to be shown.
1231 * @param endPosition The (inclusive) position of the last child to be
1232 * shown. Specify {@link #NO_POSITION} if the last child should be
1233 * the last available child from the adapter.
1234 * @param maxHeight The maximum height that will be returned (if all the
1235 * children don't fit in this value, this value will be
1236 * returned).
1237 * @param disallowPartialChildPosition In general, whether the returned
1238 * height should only contain entire children. This is more
1239 * powerful--it is the first inclusive position at which partial
1240 * children will not be allowed. Example: it looks nice to have
1241 * at least 3 completely visible children, and in portrait this
1242 * will most likely fit; but in landscape there could be times
1243 * when even 2 children can not be completely shown, so a value
1244 * of 2 (remember, inclusive) would be good (assuming
1245 * startPosition is 0).
1246 * @return The height of this ListView with the given children.
1247 */
1248 final int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition,
1249 final int maxHeight, int disallowPartialChildPosition) {
1250
1251 final ListAdapter adapter = mAdapter;
1252 if (adapter == null) {
1253 return mListPadding.top + mListPadding.bottom;
1254 }
1255
1256 // Include the padding of the list
1257 int returnedHeight = mListPadding.top + mListPadding.bottom;
1258 final int dividerHeight = ((mDividerHeight > 0) && mDivider != null) ? mDividerHeight : 0;
1259 // The previous height value that was less than maxHeight and contained
1260 // no partial children
1261 int prevHeightWithoutPartialChild = 0;
1262 int i;
1263 View child;
1264
1265 // mItemCount - 1 since endPosition parameter is inclusive
1266 endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition;
1267 final AbsListView.RecycleBin recycleBin = mRecycler;
1268 final boolean recyle = recycleOnMeasure();
Romain Guy21875052010-01-06 18:48:08 -08001269 final boolean[] isScrap = mIsScrap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270
1271 for (i = startPosition; i <= endPosition; ++i) {
Romain Guy21875052010-01-06 18:48:08 -08001272 child = obtainView(i, isScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273
Filip Gruszczynskib6824bf2015-04-13 09:16:25 -07001274 measureScrapChild(child, i, widthMeasureSpec, maxHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275
1276 if (i > 0) {
1277 // Count the divider for all but one child
1278 returnedHeight += dividerHeight;
1279 }
1280
1281 // Recycle the view before we possibly return from the method
Romain Guy9c3184cc2010-02-25 17:32:54 -08001282 if (recyle && recycleBin.shouldRecycleViewType(
1283 ((LayoutParams) child.getLayoutParams()).viewType)) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07001284 recycleBin.addScrapView(child, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
1286
1287 returnedHeight += child.getMeasuredHeight();
1288
1289 if (returnedHeight >= maxHeight) {
1290 // We went over, figure out which height to return. If returnedHeight > maxHeight,
1291 // then the i'th position did not fit completely.
1292 return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1)
1293 && (i > disallowPartialChildPosition) // We've past the min pos
1294 && (prevHeightWithoutPartialChild > 0) // We have a prev height
1295 && (returnedHeight != maxHeight) // i'th child did not fit completely
1296 ? prevHeightWithoutPartialChild
1297 : maxHeight;
1298 }
1299
1300 if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) {
1301 prevHeightWithoutPartialChild = returnedHeight;
1302 }
1303 }
1304
1305 // At this point, we went through the range of children, and they each
1306 // completely fit, so return the returnedHeight
1307 return returnedHeight;
1308 }
1309
1310 @Override
1311 int findMotionRow(int y) {
1312 int childCount = getChildCount();
1313 if (childCount > 0) {
Adam Powell84222e02010-03-11 13:42:57 -08001314 if (!mStackFromBottom) {
1315 for (int i = 0; i < childCount; i++) {
1316 View v = getChildAt(i);
1317 if (y <= v.getBottom()) {
1318 return mFirstPosition + i;
1319 }
1320 }
1321 } else {
1322 for (int i = childCount - 1; i >= 0; i--) {
1323 View v = getChildAt(i);
1324 if (y >= v.getTop()) {
1325 return mFirstPosition + i;
1326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
1328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330 return INVALID_POSITION;
1331 }
1332
1333 /**
1334 * Put a specific item at a specific location on the screen and then build
1335 * up and down from there.
1336 *
1337 * @param position The reference view to use as the starting point
1338 * @param top Pixel offset from the top of this view to the top of the
1339 * reference view.
1340 *
1341 * @return The selected view, or null if the selected view is outside the
1342 * visible area.
1343 */
1344 private View fillSpecific(int position, int top) {
1345 boolean tempIsSelected = position == mSelectedPosition;
1346 View temp = makeAndAddView(position, top, true, mListPadding.left, tempIsSelected);
1347 // Possibly changed again in fillUp if we add rows above this one.
1348 mFirstPosition = position;
1349
1350 View above;
1351 View below;
1352
1353 final int dividerHeight = mDividerHeight;
1354 if (!mStackFromBottom) {
1355 above = fillUp(position - 1, temp.getTop() - dividerHeight);
1356 // This will correct for the top of the first view not touching the top of the list
1357 adjustViewsUpOrDown();
1358 below = fillDown(position + 1, temp.getBottom() + dividerHeight);
1359 int childCount = getChildCount();
1360 if (childCount > 0) {
1361 correctTooHigh(childCount);
1362 }
1363 } else {
1364 below = fillDown(position + 1, temp.getBottom() + dividerHeight);
1365 // This will correct for the bottom of the last view not touching the bottom of the list
1366 adjustViewsUpOrDown();
1367 above = fillUp(position - 1, temp.getTop() - dividerHeight);
1368 int childCount = getChildCount();
1369 if (childCount > 0) {
1370 correctTooLow(childCount);
1371 }
1372 }
1373
1374 if (tempIsSelected) {
1375 return temp;
1376 } else if (above != null) {
1377 return above;
1378 } else {
1379 return below;
1380 }
1381 }
1382
1383 /**
1384 * Check if we have dragged the bottom of the list too high (we have pushed the
1385 * top element off the top of the screen when we did not need to). Correct by sliding
1386 * everything back down.
1387 *
1388 * @param childCount Number of children
1389 */
1390 private void correctTooHigh(int childCount) {
1391 // First see if the last item is visible. If it is not, it is OK for the
1392 // top of the list to be pushed up.
1393 int lastPosition = mFirstPosition + childCount - 1;
1394 if (lastPosition == mItemCount - 1 && childCount > 0) {
1395
1396 // Get the last child ...
1397 final View lastChild = getChildAt(childCount - 1);
1398
1399 // ... and its bottom edge
1400 final int lastBottom = lastChild.getBottom();
1401
1402 // This is bottom of our drawable area
1403 final int end = (mBottom - mTop) - mListPadding.bottom;
1404
1405 // This is how far the bottom edge of the last view is from the bottom of the
1406 // drawable area
1407 int bottomOffset = end - lastBottom;
1408 View firstChild = getChildAt(0);
1409 final int firstTop = firstChild.getTop();
1410
1411 // Make sure we are 1) Too high, and 2) Either there are more rows above the
1412 // first row or the first row is scrolled off the top of the drawable area
1413 if (bottomOffset > 0 && (mFirstPosition > 0 || firstTop < mListPadding.top)) {
1414 if (mFirstPosition == 0) {
1415 // Don't pull the top too far down
1416 bottomOffset = Math.min(bottomOffset, mListPadding.top - firstTop);
1417 }
1418 // Move everything down
1419 offsetChildrenTopAndBottom(bottomOffset);
1420 if (mFirstPosition > 0) {
1421 // Fill the gap that was opened above mFirstPosition with more rows, if
1422 // possible
1423 fillUp(mFirstPosition - 1, firstChild.getTop() - mDividerHeight);
1424 // Close up the remaining gap
1425 adjustViewsUpOrDown();
1426 }
1427
1428 }
1429 }
1430 }
1431
1432 /**
1433 * Check if we have dragged the bottom of the list too low (we have pushed the
1434 * bottom element off the bottom of the screen when we did not need to). Correct by sliding
1435 * everything back up.
1436 *
1437 * @param childCount Number of children
1438 */
1439 private void correctTooLow(int childCount) {
1440 // First see if the first item is visible. If it is not, it is OK for the
1441 // bottom of the list to be pushed down.
1442 if (mFirstPosition == 0 && childCount > 0) {
1443
1444 // Get the first child ...
1445 final View firstChild = getChildAt(0);
1446
1447 // ... and its top edge
1448 final int firstTop = firstChild.getTop();
1449
1450 // This is top of our drawable area
1451 final int start = mListPadding.top;
1452
1453 // This is bottom of our drawable area
1454 final int end = (mBottom - mTop) - mListPadding.bottom;
1455
1456 // This is how far the top edge of the first view is from the top of the
1457 // drawable area
1458 int topOffset = firstTop - start;
1459 View lastChild = getChildAt(childCount - 1);
1460 final int lastBottom = lastChild.getBottom();
1461 int lastPosition = mFirstPosition + childCount - 1;
1462
1463 // Make sure we are 1) Too low, and 2) Either there are more rows below the
1464 // last row or the last row is scrolled off the bottom of the drawable area
Romain Guy6198ae82009-08-31 17:45:55 -07001465 if (topOffset > 0) {
1466 if (lastPosition < mItemCount - 1 || lastBottom > end) {
1467 if (lastPosition == mItemCount - 1) {
1468 // Don't pull the bottom too far up
1469 topOffset = Math.min(topOffset, lastBottom - end);
1470 }
1471 // Move everything up
1472 offsetChildrenTopAndBottom(-topOffset);
1473 if (lastPosition < mItemCount - 1) {
1474 // Fill the gap that was opened below the last position with more rows, if
1475 // possible
1476 fillDown(lastPosition + 1, lastChild.getBottom() + mDividerHeight);
1477 // Close up the remaining gap
1478 adjustViewsUpOrDown();
1479 }
1480 } else if (lastPosition == mItemCount - 1) {
1481 adjustViewsUpOrDown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483 }
1484 }
1485 }
1486
1487 @Override
1488 protected void layoutChildren() {
1489 final boolean blockLayoutRequests = mBlockLayoutRequests;
Alan Viveretted44696c2013-07-18 10:37:15 -07001490 if (blockLayoutRequests) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001491 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493
Alan Viveretted44696c2013-07-18 10:37:15 -07001494 mBlockLayoutRequests = true;
1495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 try {
1497 super.layoutChildren();
1498
1499 invalidate();
1500
1501 if (mAdapter == null) {
1502 resetList();
1503 invokeOnItemScrollListener();
1504 return;
1505 }
1506
Alan Viveretted44696c2013-07-18 10:37:15 -07001507 final int childrenTop = mListPadding.top;
1508 final int childrenBottom = mBottom - mTop - mListPadding.bottom;
1509 final int childCount = getChildCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510
Romain Guyead0d4d2009-12-08 17:33:53 -08001511 int index = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 int delta = 0;
1513
1514 View sel;
1515 View oldSel = null;
1516 View oldFirst = null;
1517 View newSel = null;
1518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 // Remember stuff we will need down below
1520 switch (mLayoutMode) {
1521 case LAYOUT_SET_SELECTION:
1522 index = mNextSelectedPosition - mFirstPosition;
1523 if (index >= 0 && index < childCount) {
1524 newSel = getChildAt(index);
1525 }
1526 break;
1527 case LAYOUT_FORCE_TOP:
1528 case LAYOUT_FORCE_BOTTOM:
1529 case LAYOUT_SPECIFIC:
1530 case LAYOUT_SYNC:
1531 break;
1532 case LAYOUT_MOVE_SELECTION:
1533 default:
1534 // Remember the previously selected view
1535 index = mSelectedPosition - mFirstPosition;
1536 if (index >= 0 && index < childCount) {
1537 oldSel = getChildAt(index);
1538 }
1539
1540 // Remember the previous first child
1541 oldFirst = getChildAt(0);
1542
1543 if (mNextSelectedPosition >= 0) {
1544 delta = mNextSelectedPosition - mSelectedPosition;
1545 }
1546
1547 // Caution: newSel might be null
1548 newSel = getChildAt(index + delta);
1549 }
1550
1551
1552 boolean dataChanged = mDataChanged;
1553 if (dataChanged) {
1554 handleDataChanged();
1555 }
1556
1557 // Handle the empty set by removing all views that are visible
1558 // and calling it a day
1559 if (mItemCount == 0) {
1560 resetList();
1561 invokeOnItemScrollListener();
1562 return;
Romain Guyb45f1242009-03-24 21:30:00 -07001563 } else if (mItemCount != mAdapter.getCount()) {
1564 throw new IllegalStateException("The content of the adapter has changed but "
1565 + "ListView did not receive a notification. Make sure the content of "
Alan Viverette7d8314d2013-09-10 11:22:53 -07001566 + "your adapter is not modified from a background thread, but only from "
1567 + "the UI thread. Make sure your adapter calls notifyDataSetChanged() "
1568 + "when its content changes. [in ListView(" + getId() + ", " + getClass()
Owen Lin3940f2d2009-08-13 15:21:16 +08001569 + ") with Adapter(" + mAdapter.getClass() + ")]");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
1571
1572 setSelectedPositionInt(mNextSelectedPosition);
1573
Alan Viverette3e141622014-02-18 17:05:13 -08001574 AccessibilityNodeInfo accessibilityFocusLayoutRestoreNode = null;
1575 View accessibilityFocusLayoutRestoreView = null;
1576 int accessibilityFocusPosition = INVALID_POSITION;
1577
1578 // Remember which child, if any, had accessibility focus. This must
1579 // occur before recycling any views, since that will clear
1580 // accessibility focus.
1581 final ViewRootImpl viewRootImpl = getViewRootImpl();
1582 if (viewRootImpl != null) {
1583 final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
1584 if (focusHost != null) {
1585 final View focusChild = getAccessibilityFocusedChild(focusHost);
1586 if (focusChild != null) {
1587 if (!dataChanged || isDirectChildHeaderOrFooter(focusChild)
1588 || focusChild.hasTransientState() || mAdapterHasStableIds) {
1589 // The views won't be changing, so try to maintain
1590 // focus on the current host and virtual view.
1591 accessibilityFocusLayoutRestoreView = focusHost;
1592 accessibilityFocusLayoutRestoreNode = viewRootImpl
1593 .getAccessibilityFocusedVirtualView();
1594 }
1595
1596 // If all else fails, maintain focus at the same
1597 // position.
1598 accessibilityFocusPosition = getPositionForView(focusChild);
1599 }
1600 }
Alan Viveretteb53c5f62013-03-15 15:50:37 -07001601 }
1602
Alan Viverette3e141622014-02-18 17:05:13 -08001603 View focusLayoutRestoreDirectChild = null;
1604 View focusLayoutRestoreView = null;
1605
1606 // Take focus back to us temporarily to avoid the eventual call to
1607 // clear focus when removing the focused child below from messing
1608 // things up when ViewAncestor assigns focus back to someone else.
Alan Viveretted44696c2013-07-18 10:37:15 -07001609 final View focusedChild = getFocusedChild();
1610 if (focusedChild != null) {
Alan Viverette3e141622014-02-18 17:05:13 -08001611 // TODO: in some cases focusedChild.getParent() == null
1612
1613 // We can remember the focused view to restore after re-layout
1614 // if the data hasn't changed, or if the focused position is a
1615 // header or footer.
1616 if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
1617 focusLayoutRestoreDirectChild = focusedChild;
1618 // Remember the specific view that had focus.
1619 focusLayoutRestoreView = findFocus();
1620 if (focusLayoutRestoreView != null) {
1621 // Tell it we are going to mess with it.
1622 focusLayoutRestoreView.onStartTemporaryDetach();
1623 }
1624 }
1625 requestFocus();
Alan Viveretted44696c2013-07-18 10:37:15 -07001626 }
1627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 // Pull all children into the RecycleBin.
1629 // These views will be reused if possible
1630 final int firstPosition = mFirstPosition;
1631 final RecycleBin recycleBin = mRecycler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 if (dataChanged) {
1633 for (int i = 0; i < childCount; i++) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07001634 recycleBin.addScrapView(getChildAt(i), firstPosition+i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
1636 } else {
1637 recycleBin.fillActiveViews(childCount, firstPosition);
1638 }
1639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 // Clear out old views
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 detachAllViewsFromParent();
Adam Powell539ee872012-02-03 19:00:49 -08001642 recycleBin.removeSkippedScrap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643
1644 switch (mLayoutMode) {
1645 case LAYOUT_SET_SELECTION:
1646 if (newSel != null) {
1647 sel = fillFromSelection(newSel.getTop(), childrenTop, childrenBottom);
1648 } else {
1649 sel = fillFromMiddle(childrenTop, childrenBottom);
1650 }
1651 break;
1652 case LAYOUT_SYNC:
1653 sel = fillSpecific(mSyncPosition, mSpecificTop);
1654 break;
1655 case LAYOUT_FORCE_BOTTOM:
1656 sel = fillUp(mItemCount - 1, childrenBottom);
1657 adjustViewsUpOrDown();
1658 break;
1659 case LAYOUT_FORCE_TOP:
1660 mFirstPosition = 0;
1661 sel = fillFromTop(childrenTop);
1662 adjustViewsUpOrDown();
1663 break;
1664 case LAYOUT_SPECIFIC:
1665 sel = fillSpecific(reconcileSelectedPosition(), mSpecificTop);
1666 break;
1667 case LAYOUT_MOVE_SELECTION:
1668 sel = moveSelection(oldSel, newSel, delta, childrenTop, childrenBottom);
1669 break;
1670 default:
1671 if (childCount == 0) {
1672 if (!mStackFromBottom) {
1673 final int position = lookForSelectablePosition(0, true);
1674 setSelectedPositionInt(position);
1675 sel = fillFromTop(childrenTop);
1676 } else {
1677 final int position = lookForSelectablePosition(mItemCount - 1, false);
1678 setSelectedPositionInt(position);
1679 sel = fillUp(mItemCount - 1, childrenBottom);
1680 }
1681 } else {
1682 if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) {
1683 sel = fillSpecific(mSelectedPosition,
1684 oldSel == null ? childrenTop : oldSel.getTop());
1685 } else if (mFirstPosition < mItemCount) {
1686 sel = fillSpecific(mFirstPosition,
1687 oldFirst == null ? childrenTop : oldFirst.getTop());
1688 } else {
1689 sel = fillSpecific(0, childrenTop);
1690 }
1691 }
1692 break;
1693 }
1694
1695 // Flush any cached views that did not get reused above
1696 recycleBin.scrapActiveViews();
1697
1698 if (sel != null) {
Alan Viverette3e141622014-02-18 17:05:13 -08001699 // The current selected item should get focus if items are
1700 // focusable.
1701 if (mItemsCanFocus && hasFocus() && !sel.hasFocus()) {
1702 final boolean focusWasTaken = (sel == focusLayoutRestoreDirectChild &&
1703 focusLayoutRestoreView != null &&
1704 focusLayoutRestoreView.requestFocus()) || sel.requestFocus();
1705 if (!focusWasTaken) {
1706 // Selected item didn't take focus, but we still want to
1707 // make sure something else outside of the selected view
1708 // has focus.
Romain Guy3616a412009-09-15 13:50:37 -07001709 final View focused = getFocusedChild();
1710 if (focused != null) {
1711 focused.clearFocus();
1712 }
Dianne Hackborn079e2352010-10-18 17:02:43 -07001713 positionSelector(INVALID_POSITION, sel);
Alan Viverette3e141622014-02-18 17:05:13 -08001714 } else {
1715 sel.setSelected(false);
1716 mSelectorRect.setEmpty();
Romain Guy3616a412009-09-15 13:50:37 -07001717 }
1718 } else {
Dianne Hackborn079e2352010-10-18 17:02:43 -07001719 positionSelector(INVALID_POSITION, sel);
Romain Guy3616a412009-09-15 13:50:37 -07001720 }
1721 mSelectedTop = sel.getTop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 } else {
Alan Viverettee3c433a2014-06-19 12:48:45 -07001723 final boolean inTouchMode = mTouchMode == TOUCH_MODE_TAP
1724 || mTouchMode == TOUCH_MODE_DONE_WAITING;
1725 if (inTouchMode) {
1726 // If the user's finger is down, select the motion position.
Alan Viveretted44696c2013-07-18 10:37:15 -07001727 final View child = getChildAt(mMotionPosition - mFirstPosition);
Alan Viverettee3c433a2014-06-19 12:48:45 -07001728 if (child != null) {
Alan Viveretted44696c2013-07-18 10:37:15 -07001729 positionSelector(mMotionPosition, child);
1730 }
Alan Viverettee3c433a2014-06-19 12:48:45 -07001731 } else if (mSelectorPosition != INVALID_POSITION) {
1732 // If we had previously positioned the selector somewhere,
1733 // put it back there. It might not match up with the data,
1734 // but it's transitioning out so it's not a big deal.
1735 final View child = getChildAt(mSelectorPosition - mFirstPosition);
1736 if (child != null) {
1737 positionSelector(mSelectorPosition, child);
1738 }
Romain Guy3616a412009-09-15 13:50:37 -07001739 } else {
Alan Viverettee3c433a2014-06-19 12:48:45 -07001740 // Otherwise, clear selection.
Romain Guy3616a412009-09-15 13:50:37 -07001741 mSelectedTop = 0;
1742 mSelectorRect.setEmpty();
1743 }
Alan Viverette3e141622014-02-18 17:05:13 -08001744
1745 // Even if there is not selected position, we may need to
1746 // restore focus (i.e. something focusable in touch mode).
1747 if (hasFocus() && focusLayoutRestoreView != null) {
1748 focusLayoutRestoreView.requestFocus();
1749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
1751
Alan Viverette3e141622014-02-18 17:05:13 -08001752 // Attempt to restore accessibility focus, if necessary.
Alan Viverette2e6fc8c2014-02-24 11:09:18 -08001753 if (viewRootImpl != null) {
1754 final View newAccessibilityFocusedView = viewRootImpl.getAccessibilityFocusedHost();
1755 if (newAccessibilityFocusedView == null) {
1756 if (accessibilityFocusLayoutRestoreView != null
1757 && accessibilityFocusLayoutRestoreView.isAttachedToWindow()) {
1758 final AccessibilityNodeProvider provider =
1759 accessibilityFocusLayoutRestoreView.getAccessibilityNodeProvider();
1760 if (accessibilityFocusLayoutRestoreNode != null && provider != null) {
1761 final int virtualViewId = AccessibilityNodeInfo.getVirtualDescendantId(
1762 accessibilityFocusLayoutRestoreNode.getSourceNodeId());
1763 provider.performAction(virtualViewId,
1764 AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null);
1765 } else {
1766 accessibilityFocusLayoutRestoreView.requestAccessibilityFocus();
1767 }
1768 } else if (accessibilityFocusPosition != INVALID_POSITION) {
1769 // Bound the position within the visible children.
1770 final int position = MathUtils.constrain(
1771 accessibilityFocusPosition - mFirstPosition, 0,
1772 getChildCount() - 1);
1773 final View restoreView = getChildAt(position);
1774 if (restoreView != null) {
1775 restoreView.requestAccessibilityFocus();
1776 }
Alan Viverette68207512013-08-22 12:33:07 -07001777 }
alanv30ee76c2012-09-07 10:31:16 -07001778 }
1779 }
1780
Alan Viverette3e141622014-02-18 17:05:13 -08001781 // Tell focus view we are done mucking with it, if it is still in
1782 // our view hierarchy.
1783 if (focusLayoutRestoreView != null
1784 && focusLayoutRestoreView.getWindowToken() != null) {
1785 focusLayoutRestoreView.onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 }
1787
1788 mLayoutMode = LAYOUT_NORMAL;
1789 mDataChanged = false;
Adam Powell161abf32012-05-23 17:22:49 -07001790 if (mPositionScrollAfterLayout != null) {
1791 post(mPositionScrollAfterLayout);
1792 mPositionScrollAfterLayout = null;
1793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 mNeedSync = false;
1795 setNextSelectedPositionInt(mSelectedPosition);
1796
1797 updateScrollIndicators();
1798
1799 if (mItemCount > 0) {
1800 checkSelectionChanged();
1801 }
1802
1803 invokeOnItemScrollListener();
1804 } finally {
1805 if (!blockLayoutRequests) {
1806 mBlockLayoutRequests = false;
1807 }
1808 }
1809 }
1810
1811 /**
Alan Viverette3e141622014-02-18 17:05:13 -08001812 * @param child a direct child of this list.
1813 * @return Whether child is a header or footer view.
1814 */
1815 private boolean isDirectChildHeaderOrFooter(View child) {
1816 final ArrayList<FixedViewInfo> headers = mHeaderViewInfos;
1817 final int numHeaders = headers.size();
1818 for (int i = 0; i < numHeaders; i++) {
1819 if (child == headers.get(i).view) {
1820 return true;
1821 }
1822 }
1823
1824 final ArrayList<FixedViewInfo> footers = mFooterViewInfos;
1825 final int numFooters = footers.size();
1826 for (int i = 0; i < numFooters; i++) {
1827 if (child == footers.get(i).view) {
1828 return true;
1829 }
1830 }
1831
1832 return false;
1833 }
1834
1835 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 * Obtain the view and add it to our list of children. The view can be made
1837 * fresh, converted from an unused view, or used as is if it was in the
1838 * recycle bin.
1839 *
1840 * @param position Logical position in the list
1841 * @param y Top or bottom edge of the view to add
1842 * @param flow If flow is true, align top edge to y. If false, align bottom
1843 * edge to y.
1844 * @param childrenLeft Left edge where children should be positioned
1845 * @param selected Is this position selected?
1846 * @return View that was added
1847 */
1848 private View makeAndAddView(int position, int y, boolean flow, int childrenLeft,
1849 boolean selected) {
1850 View child;
1851
1852
1853 if (!mDataChanged) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07001854 // Try to use an existing view for this position
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 child = mRecycler.getActiveView(position);
1856 if (child != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 // Found it -- we're using an existing child
1858 // This just needs to be positioned
1859 setupChild(child, position, y, flow, childrenLeft, selected, true);
1860
1861 return child;
1862 }
1863 }
1864
1865 // Make a new view for this position, or convert an unused view if possible
Romain Guy21875052010-01-06 18:48:08 -08001866 child = obtainView(position, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867
1868 // This needs to be positioned and measured
Romain Guy21875052010-01-06 18:48:08 -08001869 setupChild(child, position, y, flow, childrenLeft, selected, mIsScrap[0]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870
1871 return child;
1872 }
1873
1874 /**
1875 * Add a view as a child and make sure it is measured (if necessary) and
1876 * positioned properly.
1877 *
1878 * @param child The view to add
1879 * @param position The position of this child
1880 * @param y The y position relative to which this view will be positioned
1881 * @param flowDown If true, align top edge to y. If false, align bottom
1882 * edge to y.
1883 * @param childrenLeft Left edge where children should be positioned
1884 * @param selected Is this position selected?
1885 * @param recycled Has this view been pulled from the recycle bin? If so it
1886 * does not need to be remeasured.
1887 */
1888 private void setupChild(View child, int position, int y, boolean flowDown, int childrenLeft,
1889 boolean selected, boolean recycled) {
Romain Guy5fade8c2013-07-10 16:36:18 -07001890 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "setupListItem");
1891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 final boolean isSelected = selected && shouldShowSelector();
1893 final boolean updateChildSelected = isSelected != child.isSelected();
Romain Guy3616a412009-09-15 13:50:37 -07001894 final int mode = mTouchMode;
1895 final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL &&
1896 mMotionPosition == position;
1897 final boolean updateChildPressed = isPressed != child.isPressed();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();
1899
1900 // Respect layout params that are already in the view. Otherwise make some up...
1901 // noinspection unchecked
1902 AbsListView.LayoutParams p = (AbsListView.LayoutParams) child.getLayoutParams();
1903 if (p == null) {
Adam Powellaebd28f2012-02-22 10:31:16 -08001904 p = (AbsListView.LayoutParams) generateDefaultLayoutParams();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 }
1906 p.viewType = mAdapter.getItemViewType(position);
1907
Romain Guy0bf88592010-03-02 13:38:44 -08001908 if ((recycled && !p.forceAdd) || (p.recycledHeaderFooter &&
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001909 p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 attachViewToParent(child, flowDown ? -1 : 0, p);
1911 } else {
Romain Guy0bf88592010-03-02 13:38:44 -08001912 p.forceAdd = false;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001913 if (p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
1914 p.recycledHeaderFooter = true;
1915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 addViewInLayout(child, flowDown ? -1 : 0, p, true);
1917 }
1918
1919 if (updateChildSelected) {
1920 child.setSelected(isSelected);
1921 }
1922
Romain Guy3616a412009-09-15 13:50:37 -07001923 if (updateChildPressed) {
1924 child.setPressed(isPressed);
1925 }
1926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
1928 if (child instanceof Checkable) {
1929 ((Checkable) child).setChecked(mCheckStates.get(position));
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001930 } else if (getContext().getApplicationInfo().targetSdkVersion
1931 >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1932 child.setActivated(mCheckStates.get(position));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934 }
1935
1936 if (needToMeasure) {
1937 int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
1938 mListPadding.left + mListPadding.right, p.width);
1939 int lpHeight = p.height;
1940 int childHeightSpec;
1941 if (lpHeight > 0) {
1942 childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
1943 } else {
Filip Gruszczynskib6824bf2015-04-13 09:16:25 -07001944 childHeightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(),
1945 MeasureSpec.UNSPECIFIED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
1947 child.measure(childWidthSpec, childHeightSpec);
1948 } else {
1949 cleanupLayoutState(child);
1950 }
1951
1952 final int w = child.getMeasuredWidth();
1953 final int h = child.getMeasuredHeight();
1954 final int childTop = flowDown ? y : y - h;
1955
1956 if (needToMeasure) {
1957 final int childRight = childrenLeft + w;
1958 final int childBottom = childTop + h;
1959 child.layout(childrenLeft, childTop, childRight, childBottom);
1960 } else {
1961 child.offsetLeftAndRight(childrenLeft - child.getLeft());
1962 child.offsetTopAndBottom(childTop - child.getTop());
1963 }
1964
1965 if (mCachingStarted && !child.isDrawingCacheEnabled()) {
1966 child.setDrawingCacheEnabled(true);
1967 }
Dianne Hackborn079e2352010-10-18 17:02:43 -07001968
1969 if (recycled && (((AbsListView.LayoutParams)child.getLayoutParams()).scrappedFromPosition)
1970 != position) {
1971 child.jumpDrawablesToCurrentState();
1972 }
Romain Guy5fade8c2013-07-10 16:36:18 -07001973
1974 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
1976
1977 @Override
1978 protected boolean canAnimate() {
1979 return super.canAnimate() && mItemCount > 0;
1980 }
1981
1982 /**
1983 * Sets the currently selected item. If in touch mode, the item will not be selected
1984 * but it will still be positioned appropriately. If the specified selection position
1985 * is less than 0, then the item at position 0 will be selected.
1986 *
1987 * @param position Index (starting at 0) of the data item to be selected.
1988 */
1989 @Override
1990 public void setSelection(int position) {
1991 setSelectionFromTop(position, 0);
1992 }
1993
1994 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 * Makes the item at the supplied position selected.
Mike Cleronf116bf82009-09-27 19:14:12 -07001996 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 * @param position the position of the item to select
1998 */
1999 @Override
2000 void setSelectionInt(int position) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 setNextSelectedPositionInt(position);
Mike Cleronf116bf82009-09-27 19:14:12 -07002002 boolean awakeScrollbars = false;
2003
2004 final int selectedPosition = mSelectedPosition;
2005
2006 if (selectedPosition >= 0) {
2007 if (position == selectedPosition - 1) {
2008 awakeScrollbars = true;
2009 } else if (position == selectedPosition + 1) {
2010 awakeScrollbars = true;
2011 }
2012 }
2013
Adam Powell1fa179ef2012-04-12 15:01:40 -07002014 if (mPositionScroller != null) {
2015 mPositionScroller.stop();
2016 }
2017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 layoutChildren();
Mike Cleronf116bf82009-09-27 19:14:12 -07002019
2020 if (awakeScrollbars) {
2021 awakenScrollBars();
2022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 }
2024
2025 /**
2026 * Find a position that can be selected (i.e., is not a separator).
2027 *
2028 * @param position The starting position to look at.
2029 * @param lookDown Whether to look down for other positions.
2030 * @return The next selectable position starting at position and then searching either up or
2031 * down. Returns {@link #INVALID_POSITION} if nothing can be found.
2032 */
2033 @Override
2034 int lookForSelectablePosition(int position, boolean lookDown) {
2035 final ListAdapter adapter = mAdapter;
2036 if (adapter == null || isInTouchMode()) {
2037 return INVALID_POSITION;
2038 }
2039
2040 final int count = adapter.getCount();
2041 if (!mAreAllItemsSelectable) {
2042 if (lookDown) {
2043 position = Math.max(0, position);
2044 while (position < count && !adapter.isEnabled(position)) {
2045 position++;
2046 }
2047 } else {
2048 position = Math.min(position, count - 1);
2049 while (position >= 0 && !adapter.isEnabled(position)) {
2050 position--;
2051 }
2052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002054
2055 if (position < 0 || position >= count) {
2056 return INVALID_POSITION;
2057 }
2058
2059 return position;
2060 }
2061
2062 /**
2063 * Find a position that can be selected (i.e., is not a separator). If there
2064 * are no selectable positions in the specified direction from the starting
2065 * position, searches in the opposite direction from the starting position
2066 * to the current position.
2067 *
2068 * @param current the current position
2069 * @param position the starting position
2070 * @param lookDown whether to look down for other positions
2071 * @return the next selectable position, or {@link #INVALID_POSITION} if
2072 * nothing can be found
2073 */
2074 int lookForSelectablePositionAfter(int current, int position, boolean lookDown) {
2075 final ListAdapter adapter = mAdapter;
2076 if (adapter == null || isInTouchMode()) {
2077 return INVALID_POSITION;
2078 }
2079
2080 // First check after the starting position in the specified direction.
2081 final int after = lookForSelectablePosition(position, lookDown);
2082 if (after != INVALID_POSITION) {
2083 return after;
2084 }
2085
2086 // Then check between the starting position and the current position.
2087 final int count = adapter.getCount();
2088 current = MathUtils.constrain(current, -1, count - 1);
2089 if (lookDown) {
2090 position = Math.min(position - 1, count - 1);
2091 while ((position > current) && !adapter.isEnabled(position)) {
2092 position--;
2093 }
2094 if (position <= current) {
2095 return INVALID_POSITION;
2096 }
2097 } else {
2098 position = Math.max(0, position + 1);
2099 while ((position < current) && !adapter.isEnabled(position)) {
2100 position++;
2101 }
2102 if (position >= current) {
2103 return INVALID_POSITION;
2104 }
2105 }
2106
2107 return position;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 }
2109
2110 /**
2111 * setSelectionAfterHeaderView set the selection to be the first list item
2112 * after the header views.
2113 */
2114 public void setSelectionAfterHeaderView() {
2115 final int count = mHeaderViewInfos.size();
2116 if (count > 0) {
2117 mNextSelectedPosition = 0;
2118 return;
2119 }
2120
2121 if (mAdapter != null) {
2122 setSelection(count);
2123 } else {
2124 mNextSelectedPosition = count;
2125 mLayoutMode = LAYOUT_SET_SELECTION;
2126 }
2127
2128 }
2129
2130 @Override
2131 public boolean dispatchKeyEvent(KeyEvent event) {
2132 // Dispatch in the normal way
2133 boolean handled = super.dispatchKeyEvent(event);
2134 if (!handled) {
2135 // If we didn't handle it...
2136 View focused = getFocusedChild();
2137 if (focused != null && event.getAction() == KeyEvent.ACTION_DOWN) {
2138 // ... and our focused child didn't handle it
2139 // ... give it to ourselves so we can scroll if necessary
2140 handled = onKeyDown(event.getKeyCode(), event);
2141 }
2142 }
2143 return handled;
2144 }
2145
2146 @Override
2147 public boolean onKeyDown(int keyCode, KeyEvent event) {
2148 return commonKey(keyCode, 1, event);
2149 }
2150
2151 @Override
2152 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2153 return commonKey(keyCode, repeatCount, event);
2154 }
2155
2156 @Override
2157 public boolean onKeyUp(int keyCode, KeyEvent event) {
2158 return commonKey(keyCode, 1, event);
2159 }
2160
2161 private boolean commonKey(int keyCode, int count, KeyEvent event) {
Adam Powell31986b52013-09-24 14:53:30 -07002162 if (mAdapter == null || !isAttachedToWindow()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 return false;
2164 }
2165
2166 if (mDataChanged) {
2167 layoutChildren();
2168 }
2169
2170 boolean handled = false;
2171 int action = event.getAction();
2172
2173 if (action != KeyEvent.ACTION_UP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 switch (keyCode) {
2175 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002176 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002177 handled = resurrectSelectionIfNeeded();
2178 if (!handled) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002179 while (count-- > 0) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002180 if (arrowScroll(FOCUS_UP)) {
2181 handled = true;
2182 } else {
2183 break;
2184 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002187 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002188 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 }
2190 break;
2191
2192 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002193 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002194 handled = resurrectSelectionIfNeeded();
2195 if (!handled) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002196 while (count-- > 0) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002197 if (arrowScroll(FOCUS_DOWN)) {
2198 handled = true;
2199 } else {
2200 break;
2201 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002204 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002205 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 }
2207 break;
2208
2209 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002210 if (event.hasNoModifiers()) {
2211 handled = handleHorizontalFocusWithinListItem(View.FOCUS_LEFT);
2212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002216 if (event.hasNoModifiers()) {
2217 handled = handleHorizontalFocusWithinListItem(View.FOCUS_RIGHT);
2218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 break;
2220
2221 case KeyEvent.KEYCODE_DPAD_CENTER:
2222 case KeyEvent.KEYCODE_ENTER:
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002223 if (event.hasNoModifiers()) {
2224 handled = resurrectSelectionIfNeeded();
2225 if (!handled
2226 && event.getRepeatCount() == 0 && getChildCount() > 0) {
2227 keyPressed();
2228 handled = true;
2229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 break;
2232
2233 case KeyEvent.KEYCODE_SPACE:
2234 if (mPopup == null || !mPopup.isShowing()) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002235 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002236 handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002237 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002238 handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_UP);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 }
2240 handled = true;
2241 }
2242 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002243
2244 case KeyEvent.KEYCODE_PAGE_UP:
2245 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002246 handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_UP);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002247 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002248 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002249 }
2250 break;
2251
2252 case KeyEvent.KEYCODE_PAGE_DOWN:
2253 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002254 handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002255 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002256 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002257 }
2258 break;
2259
2260 case KeyEvent.KEYCODE_MOVE_HOME:
2261 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002262 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002263 }
2264 break;
2265
2266 case KeyEvent.KEYCODE_MOVE_END:
2267 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002268 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002269 }
2270 break;
2271
2272 case KeyEvent.KEYCODE_TAB:
2273 // XXX Sometimes it is useful to be able to TAB through the items in
2274 // a ListView sequentially. Unfortunately this can create an
2275 // asymmetry in TAB navigation order unless the list selection
2276 // always reverts to the top or bottom when receiving TAB focus from
2277 // another widget. Leaving this behavior disabled for now but
2278 // perhaps it should be configurable (and more comprehensive).
2279 if (false) {
2280 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002281 handled = resurrectSelectionIfNeeded() || arrowScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002282 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002283 handled = resurrectSelectionIfNeeded() || arrowScroll(FOCUS_UP);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002284 }
2285 }
2286 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 }
2288 }
2289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 if (handled) {
2291 return true;
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002294 if (sendToTextFilter(keyCode, count, event)) {
2295 return true;
2296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002298 switch (action) {
2299 case KeyEvent.ACTION_DOWN:
2300 return super.onKeyDown(keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002302 case KeyEvent.ACTION_UP:
2303 return super.onKeyUp(keyCode, event);
2304
2305 case KeyEvent.ACTION_MULTIPLE:
2306 return super.onKeyMultiple(keyCode, count, event);
2307
2308 default: // shouldn't happen
2309 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
2311 }
2312
2313 /**
2314 * Scrolls up or down by the number of items currently present on screen.
2315 *
2316 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2317 * @return whether selection was moved
2318 */
2319 boolean pageScroll(int direction) {
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002320 final int nextPage;
2321 final boolean down;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322
2323 if (direction == FOCUS_UP) {
2324 nextPage = Math.max(0, mSelectedPosition - getChildCount() - 1);
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002325 down = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 } else if (direction == FOCUS_DOWN) {
2327 nextPage = Math.min(mItemCount - 1, mSelectedPosition + getChildCount() - 1);
2328 down = true;
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002329 } else {
2330 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 }
2332
2333 if (nextPage >= 0) {
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002334 final int position = lookForSelectablePositionAfter(mSelectedPosition, nextPage, down);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 if (position >= 0) {
2336 mLayoutMode = LAYOUT_SPECIFIC;
2337 mSpecificTop = mPaddingTop + getVerticalFadingEdgeLength();
2338
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002339 if (down && (position > (mItemCount - getChildCount()))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 mLayoutMode = LAYOUT_FORCE_BOTTOM;
2341 }
2342
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002343 if (!down && (position < getChildCount())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 mLayoutMode = LAYOUT_FORCE_TOP;
2345 }
2346
2347 setSelectionInt(position);
2348 invokeOnItemScrollListener();
Mike Cleronf116bf82009-09-27 19:14:12 -07002349 if (!awakenScrollBars()) {
2350 invalidate();
2351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352
2353 return true;
2354 }
2355 }
2356
2357 return false;
2358 }
2359
2360 /**
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002361 * Go to the last or first item if possible (not worrying about panning
2362 * across or navigating within the internal focus of the currently selected
2363 * item.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 *
2365 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 * @return whether selection was moved
2367 */
2368 boolean fullScroll(int direction) {
2369 boolean moved = false;
2370 if (direction == FOCUS_UP) {
2371 if (mSelectedPosition != 0) {
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002372 final int position = lookForSelectablePositionAfter(mSelectedPosition, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 if (position >= 0) {
2374 mLayoutMode = LAYOUT_FORCE_TOP;
2375 setSelectionInt(position);
2376 invokeOnItemScrollListener();
2377 }
2378 moved = true;
2379 }
2380 } else if (direction == FOCUS_DOWN) {
Alan Viveretteaf9c5ea2013-06-13 13:27:59 -07002381 final int lastItem = (mItemCount - 1);
2382 if (mSelectedPosition < lastItem) {
2383 final int position = lookForSelectablePositionAfter(
2384 mSelectedPosition, lastItem, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 if (position >= 0) {
2386 mLayoutMode = LAYOUT_FORCE_BOTTOM;
2387 setSelectionInt(position);
2388 invokeOnItemScrollListener();
2389 }
2390 moved = true;
2391 }
2392 }
2393
Mike Cleronf116bf82009-09-27 19:14:12 -07002394 if (moved && !awakenScrollBars()) {
2395 awakenScrollBars();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 invalidate();
2397 }
2398
2399 return moved;
2400 }
2401
2402 /**
2403 * To avoid horizontal focus searches changing the selected item, we
2404 * manually focus search within the selected item (as applicable), and
2405 * prevent focus from jumping to something within another item.
2406 * @param direction one of {View.FOCUS_LEFT, View.FOCUS_RIGHT}
2407 * @return Whether this consumes the key event.
2408 */
2409 private boolean handleHorizontalFocusWithinListItem(int direction) {
2410 if (direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT) {
Romain Guy304eefa2009-03-24 20:01:49 -07002411 throw new IllegalArgumentException("direction must be one of"
2412 + " {View.FOCUS_LEFT, View.FOCUS_RIGHT}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 }
2414
2415 final int numChildren = getChildCount();
2416 if (mItemsCanFocus && numChildren > 0 && mSelectedPosition != INVALID_POSITION) {
2417 final View selectedView = getSelectedView();
Romain Guy304eefa2009-03-24 20:01:49 -07002418 if (selectedView != null && selectedView.hasFocus() &&
2419 selectedView instanceof ViewGroup) {
2420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 final View currentFocus = selectedView.findFocus();
2422 final View nextFocus = FocusFinder.getInstance().findNextFocus(
Romain Guy304eefa2009-03-24 20:01:49 -07002423 (ViewGroup) selectedView, currentFocus, direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 if (nextFocus != null) {
2425 // do the math to get interesting rect in next focus' coordinates
Kenji Sugimoto827bb442014-04-10 17:46:23 +09002426 Rect focusedRect = mTempRect;
2427 if (currentFocus != null) {
2428 currentFocus.getFocusedRect(focusedRect);
2429 offsetDescendantRectToMyCoords(currentFocus, focusedRect);
2430 offsetRectIntoDescendantCoords(nextFocus, focusedRect);
2431 } else {
2432 focusedRect = null;
2433 }
2434 if (nextFocus.requestFocus(direction, focusedRect)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 return true;
2436 }
2437 }
2438 // we are blocking the key from being handled (by returning true)
2439 // if the global result is going to be some other view within this
2440 // list. this is to acheive the overall goal of having
2441 // horizontal d-pad navigation remain in the current item.
Romain Guy304eefa2009-03-24 20:01:49 -07002442 final View globalNextFocus = FocusFinder.getInstance().findNextFocus(
2443 (ViewGroup) getRootView(), currentFocus, direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 if (globalNextFocus != null) {
2445 return isViewAncestorOf(globalNextFocus, this);
2446 }
2447 }
2448 }
2449 return false;
2450 }
2451
2452 /**
2453 * Scrolls to the next or previous item if possible.
2454 *
2455 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2456 *
2457 * @return whether selection was moved
2458 */
2459 boolean arrowScroll(int direction) {
2460 try {
2461 mInLayout = true;
2462 final boolean handled = arrowScrollImpl(direction);
2463 if (handled) {
2464 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2465 }
2466 return handled;
2467 } finally {
2468 mInLayout = false;
2469 }
2470 }
2471
2472 /**
Adam Powell2a939112013-03-21 17:08:38 -07002473 * Used by {@link #arrowScrollImpl(int)} to help determine the next selected position
Jaewan Kim49fc4dc2013-05-21 03:02:30 +09002474 * to move to. This return a position in the direction given if the selected item
2475 * is fully visible.
Adam Powell2a939112013-03-21 17:08:38 -07002476 *
Jaewan Kim49fc4dc2013-05-21 03:02:30 +09002477 * @param selectedView Current selected view to move from
Adam Powell2a939112013-03-21 17:08:38 -07002478 * @param selectedPos Current selected position to move from
2479 * @param direction Direction to move in
2480 * @return Desired selected position after moving in the given direction
2481 */
Jaewan Kim49fc4dc2013-05-21 03:02:30 +09002482 private final int nextSelectedPositionForDirection(
2483 View selectedView, int selectedPos, int direction) {
Adam Powell2a939112013-03-21 17:08:38 -07002484 int nextSelected;
Jaewan Kim49fc4dc2013-05-21 03:02:30 +09002485
Adam Powell2a939112013-03-21 17:08:38 -07002486 if (direction == View.FOCUS_DOWN) {
Jaewan Kim49fc4dc2013-05-21 03:02:30 +09002487 final int listBottom = getHeight() - mListPadding.bottom;
2488 if (selectedView != null && selectedView.getBottom() <= listBottom) {
2489 nextSelected = selectedPos != INVALID_POSITION && selectedPos >= mFirstPosition ?
2490 selectedPos + 1 :
2491 mFirstPosition;
2492 } else {
2493 return INVALID_POSITION;
2494 }
Adam Powell2a939112013-03-21 17:08:38 -07002495 } else {
Jaewan Kim49fc4dc2013-05-21 03:02:30 +09002496 final int listTop = mListPadding.top;
2497 if (selectedView != null && selectedView.getTop() >= listTop) {
2498 final int lastPos = mFirstPosition + getChildCount() - 1;
2499 nextSelected = selectedPos != INVALID_POSITION && selectedPos <= lastPos ?
2500 selectedPos - 1 :
2501 lastPos;
2502 } else {
2503 return INVALID_POSITION;
2504 }
Adam Powell2a939112013-03-21 17:08:38 -07002505 }
2506
2507 if (nextSelected < 0 || nextSelected >= mAdapter.getCount()) {
2508 return INVALID_POSITION;
2509 }
2510 return lookForSelectablePosition(nextSelected, direction == View.FOCUS_DOWN);
2511 }
2512
2513 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 * Handle an arrow scroll going up or down. Take into account whether items are selectable,
2515 * whether there are focusable items etc.
2516 *
2517 * @param direction Either {@link android.view.View#FOCUS_UP} or {@link android.view.View#FOCUS_DOWN}.
2518 * @return Whether any scrolling, selection or focus change occured.
2519 */
2520 private boolean arrowScrollImpl(int direction) {
2521 if (getChildCount() <= 0) {
2522 return false;
2523 }
2524
2525 View selectedView = getSelectedView();
Dianne Hackborn079e2352010-10-18 17:02:43 -07002526 int selectedPos = mSelectedPosition;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527
Jaewan Kim49fc4dc2013-05-21 03:02:30 +09002528 int nextSelectedPosition = nextSelectedPositionForDirection(selectedView, selectedPos, direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 int amountToScroll = amountToScroll(direction, nextSelectedPosition);
2530
2531 // if we are moving focus, we may OVERRIDE the default behavior
2532 final ArrowScrollFocusResult focusResult = mItemsCanFocus ? arrowScrollFocused(direction) : null;
2533 if (focusResult != null) {
2534 nextSelectedPosition = focusResult.getSelectedPosition();
2535 amountToScroll = focusResult.getAmountToScroll();
2536 }
2537
2538 boolean needToRedraw = focusResult != null;
2539 if (nextSelectedPosition != INVALID_POSITION) {
2540 handleNewSelectionChange(selectedView, direction, nextSelectedPosition, focusResult != null);
2541 setSelectedPositionInt(nextSelectedPosition);
2542 setNextSelectedPositionInt(nextSelectedPosition);
2543 selectedView = getSelectedView();
Dianne Hackborn079e2352010-10-18 17:02:43 -07002544 selectedPos = nextSelectedPosition;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 if (mItemsCanFocus && focusResult == null) {
2546 // there was no new view found to take focus, make sure we
2547 // don't leave focus with the old selection
2548 final View focused = getFocusedChild();
2549 if (focused != null) {
2550 focused.clearFocus();
2551 }
2552 }
2553 needToRedraw = true;
2554 checkSelectionChanged();
2555 }
2556
2557 if (amountToScroll > 0) {
2558 scrollListItemsBy((direction == View.FOCUS_UP) ? amountToScroll : -amountToScroll);
2559 needToRedraw = true;
2560 }
2561
2562 // if we didn't find a new focusable, make sure any existing focused
2563 // item that was panned off screen gives up focus.
2564 if (mItemsCanFocus && (focusResult == null)
2565 && selectedView != null && selectedView.hasFocus()) {
2566 final View focused = selectedView.findFocus();
Kenji Sugimoto827bb442014-04-10 17:46:23 +09002567 if (focused != null) {
2568 if (!isViewAncestorOf(focused, this) || distanceToView(focused) > 0) {
2569 focused.clearFocus();
2570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
2572 }
2573
2574 // if the current selection is panned off, we need to remove the selection
2575 if (nextSelectedPosition == INVALID_POSITION && selectedView != null
2576 && !isViewAncestorOf(selectedView, this)) {
2577 selectedView = null;
2578 hideSelector();
2579
2580 // but we don't want to set the ressurect position (that would make subsequent
2581 // unhandled key events bring back the item we just scrolled off!)
2582 mResurrectToPosition = INVALID_POSITION;
2583 }
2584
2585 if (needToRedraw) {
2586 if (selectedView != null) {
Alan Viverettede399392014-05-01 17:20:55 -07002587 positionSelectorLikeFocus(selectedPos, selectedView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 mSelectedTop = selectedView.getTop();
2589 }
Mike Cleronf116bf82009-09-27 19:14:12 -07002590 if (!awakenScrollBars()) {
2591 invalidate();
2592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 invokeOnItemScrollListener();
2594 return true;
2595 }
2596
2597 return false;
2598 }
2599
2600 /**
2601 * When selection changes, it is possible that the previously selected or the
2602 * next selected item will change its size. If so, we need to offset some folks,
2603 * and re-layout the items as appropriate.
2604 *
2605 * @param selectedView The currently selected view (before changing selection).
2606 * should be <code>null</code> if there was no previous selection.
2607 * @param direction Either {@link android.view.View#FOCUS_UP} or
2608 * {@link android.view.View#FOCUS_DOWN}.
2609 * @param newSelectedPosition The position of the next selection.
2610 * @param newFocusAssigned whether new focus was assigned. This matters because
2611 * when something has focus, we don't want to show selection (ugh).
2612 */
2613 private void handleNewSelectionChange(View selectedView, int direction, int newSelectedPosition,
2614 boolean newFocusAssigned) {
2615 if (newSelectedPosition == INVALID_POSITION) {
2616 throw new IllegalArgumentException("newSelectedPosition needs to be valid");
2617 }
2618
2619 // whether or not we are moving down or up, we want to preserve the
2620 // top of whatever view is on top:
2621 // - moving down: the view that had selection
2622 // - moving up: the view that is getting selection
2623 View topView;
2624 View bottomView;
2625 int topViewIndex, bottomViewIndex;
2626 boolean topSelected = false;
2627 final int selectedIndex = mSelectedPosition - mFirstPosition;
2628 final int nextSelectedIndex = newSelectedPosition - mFirstPosition;
2629 if (direction == View.FOCUS_UP) {
2630 topViewIndex = nextSelectedIndex;
2631 bottomViewIndex = selectedIndex;
2632 topView = getChildAt(topViewIndex);
2633 bottomView = selectedView;
2634 topSelected = true;
2635 } else {
2636 topViewIndex = selectedIndex;
2637 bottomViewIndex = nextSelectedIndex;
2638 topView = selectedView;
2639 bottomView = getChildAt(bottomViewIndex);
2640 }
2641
2642 final int numChildren = getChildCount();
2643
2644 // start with top view: is it changing size?
2645 if (topView != null) {
2646 topView.setSelected(!newFocusAssigned && topSelected);
2647 measureAndAdjustDown(topView, topViewIndex, numChildren);
2648 }
2649
2650 // is the bottom view changing size?
2651 if (bottomView != null) {
2652 bottomView.setSelected(!newFocusAssigned && !topSelected);
2653 measureAndAdjustDown(bottomView, bottomViewIndex, numChildren);
2654 }
2655 }
2656
2657 /**
2658 * Re-measure a child, and if its height changes, lay it out preserving its
2659 * top, and adjust the children below it appropriately.
2660 * @param child The child
2661 * @param childIndex The view group index of the child.
2662 * @param numChildren The number of children in the view group.
2663 */
2664 private void measureAndAdjustDown(View child, int childIndex, int numChildren) {
2665 int oldHeight = child.getHeight();
2666 measureItem(child);
2667 if (child.getMeasuredHeight() != oldHeight) {
2668 // lay out the view, preserving its top
2669 relayoutMeasuredItem(child);
2670
2671 // adjust views below appropriately
2672 final int heightDelta = child.getMeasuredHeight() - oldHeight;
2673 for (int i = childIndex + 1; i < numChildren; i++) {
2674 getChildAt(i).offsetTopAndBottom(heightDelta);
2675 }
2676 }
2677 }
2678
2679 /**
2680 * Measure a particular list child.
2681 * TODO: unify with setUpChild.
2682 * @param child The child.
2683 */
2684 private void measureItem(View child) {
2685 ViewGroup.LayoutParams p = child.getLayoutParams();
2686 if (p == null) {
2687 p = new ViewGroup.LayoutParams(
Romain Guy980a9382010-01-08 15:06:28 -08002688 ViewGroup.LayoutParams.MATCH_PARENT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 ViewGroup.LayoutParams.WRAP_CONTENT);
2690 }
2691
2692 int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
2693 mListPadding.left + mListPadding.right, p.width);
2694 int lpHeight = p.height;
2695 int childHeightSpec;
2696 if (lpHeight > 0) {
2697 childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
2698 } else {
Filip Gruszczynskib6824bf2015-04-13 09:16:25 -07002699 childHeightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(),
2700 MeasureSpec.UNSPECIFIED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 }
2702 child.measure(childWidthSpec, childHeightSpec);
2703 }
2704
2705 /**
2706 * Layout a child that has been measured, preserving its top position.
2707 * TODO: unify with setUpChild.
2708 * @param child The child.
2709 */
2710 private void relayoutMeasuredItem(View child) {
2711 final int w = child.getMeasuredWidth();
2712 final int h = child.getMeasuredHeight();
2713 final int childLeft = mListPadding.left;
2714 final int childRight = childLeft + w;
2715 final int childTop = child.getTop();
2716 final int childBottom = childTop + h;
2717 child.layout(childLeft, childTop, childRight, childBottom);
2718 }
2719
2720 /**
2721 * @return The amount to preview next items when arrow srolling.
2722 */
2723 private int getArrowScrollPreviewLength() {
2724 return Math.max(MIN_SCROLL_PREVIEW_PIXELS, getVerticalFadingEdgeLength());
2725 }
2726
2727 /**
2728 * Determine how much we need to scroll in order to get the next selected view
2729 * visible, with a fading edge showing below as applicable. The amount is
2730 * capped at {@link #getMaxScrollAmount()} .
2731 *
2732 * @param direction either {@link android.view.View#FOCUS_UP} or
2733 * {@link android.view.View#FOCUS_DOWN}.
2734 * @param nextSelectedPosition The position of the next selection, or
2735 * {@link #INVALID_POSITION} if there is no next selectable position
2736 * @return The amount to scroll. Note: this is always positive! Direction
2737 * needs to be taken into account when actually scrolling.
2738 */
2739 private int amountToScroll(int direction, int nextSelectedPosition) {
2740 final int listBottom = getHeight() - mListPadding.bottom;
2741 final int listTop = mListPadding.top;
2742
Justin Ho1ad11b92013-02-25 16:09:20 -08002743 int numChildren = getChildCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744
2745 if (direction == View.FOCUS_DOWN) {
2746 int indexToMakeVisible = numChildren - 1;
2747 if (nextSelectedPosition != INVALID_POSITION) {
2748 indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2749 }
Justin Ho1ad11b92013-02-25 16:09:20 -08002750 while (numChildren <= indexToMakeVisible) {
2751 // Child to view is not attached yet.
2752 addViewBelow(getChildAt(numChildren - 1), mFirstPosition + numChildren - 1);
2753 numChildren++;
2754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2756 final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2757
2758 int goalBottom = listBottom;
2759 if (positionToMakeVisible < mItemCount - 1) {
2760 goalBottom -= getArrowScrollPreviewLength();
2761 }
2762
2763 if (viewToMakeVisible.getBottom() <= goalBottom) {
2764 // item is fully visible.
2765 return 0;
2766 }
2767
2768 if (nextSelectedPosition != INVALID_POSITION
2769 && (goalBottom - viewToMakeVisible.getTop()) >= getMaxScrollAmount()) {
2770 // item already has enough of it visible, changing selection is good enough
2771 return 0;
2772 }
2773
2774 int amountToScroll = (viewToMakeVisible.getBottom() - goalBottom);
2775
2776 if ((mFirstPosition + numChildren) == mItemCount) {
2777 // last is last in list -> make sure we don't scroll past it
2778 final int max = getChildAt(numChildren - 1).getBottom() - listBottom;
2779 amountToScroll = Math.min(amountToScroll, max);
2780 }
2781
2782 return Math.min(amountToScroll, getMaxScrollAmount());
2783 } else {
2784 int indexToMakeVisible = 0;
2785 if (nextSelectedPosition != INVALID_POSITION) {
2786 indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2787 }
Justin Ho1ad11b92013-02-25 16:09:20 -08002788 while (indexToMakeVisible < 0) {
2789 // Child to view is not attached yet.
2790 addViewAbove(getChildAt(0), mFirstPosition);
2791 mFirstPosition--;
2792 indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2795 final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2796 int goalTop = listTop;
2797 if (positionToMakeVisible > 0) {
2798 goalTop += getArrowScrollPreviewLength();
2799 }
2800 if (viewToMakeVisible.getTop() >= goalTop) {
2801 // item is fully visible.
2802 return 0;
2803 }
2804
2805 if (nextSelectedPosition != INVALID_POSITION &&
2806 (viewToMakeVisible.getBottom() - goalTop) >= getMaxScrollAmount()) {
2807 // item already has enough of it visible, changing selection is good enough
2808 return 0;
2809 }
2810
2811 int amountToScroll = (goalTop - viewToMakeVisible.getTop());
2812 if (mFirstPosition == 0) {
2813 // first is first in list -> make sure we don't scroll past it
2814 final int max = listTop - getChildAt(0).getTop();
2815 amountToScroll = Math.min(amountToScroll, max);
2816 }
2817 return Math.min(amountToScroll, getMaxScrollAmount());
2818 }
2819 }
2820
2821 /**
2822 * Holds results of focus aware arrow scrolling.
2823 */
2824 static private class ArrowScrollFocusResult {
2825 private int mSelectedPosition;
2826 private int mAmountToScroll;
2827
2828 /**
2829 * How {@link android.widget.ListView#arrowScrollFocused} returns its values.
2830 */
2831 void populate(int selectedPosition, int amountToScroll) {
2832 mSelectedPosition = selectedPosition;
2833 mAmountToScroll = amountToScroll;
2834 }
2835
2836 public int getSelectedPosition() {
2837 return mSelectedPosition;
2838 }
2839
2840 public int getAmountToScroll() {
2841 return mAmountToScroll;
2842 }
2843 }
2844
2845 /**
2846 * @param direction either {@link android.view.View#FOCUS_UP} or
2847 * {@link android.view.View#FOCUS_DOWN}.
2848 * @return The position of the next selectable position of the views that
2849 * are currently visible, taking into account the fact that there might
2850 * be no selection. Returns {@link #INVALID_POSITION} if there is no
2851 * selectable view on screen in the given direction.
2852 */
2853 private int lookForSelectablePositionOnScreen(int direction) {
2854 final int firstPosition = mFirstPosition;
2855 if (direction == View.FOCUS_DOWN) {
2856 int startPos = (mSelectedPosition != INVALID_POSITION) ?
2857 mSelectedPosition + 1 :
2858 firstPosition;
2859 if (startPos >= mAdapter.getCount()) {
2860 return INVALID_POSITION;
2861 }
2862 if (startPos < firstPosition) {
2863 startPos = firstPosition;
2864 }
2865
2866 final int lastVisiblePos = getLastVisiblePosition();
2867 final ListAdapter adapter = getAdapter();
2868 for (int pos = startPos; pos <= lastVisiblePos; pos++) {
2869 if (adapter.isEnabled(pos)
2870 && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2871 return pos;
2872 }
2873 }
2874 } else {
2875 int last = firstPosition + getChildCount() - 1;
2876 int startPos = (mSelectedPosition != INVALID_POSITION) ?
2877 mSelectedPosition - 1 :
2878 firstPosition + getChildCount() - 1;
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002879 if (startPos < 0 || startPos >= mAdapter.getCount()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 return INVALID_POSITION;
2881 }
2882 if (startPos > last) {
2883 startPos = last;
2884 }
2885
2886 final ListAdapter adapter = getAdapter();
2887 for (int pos = startPos; pos >= firstPosition; pos--) {
2888 if (adapter.isEnabled(pos)
2889 && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2890 return pos;
2891 }
2892 }
2893 }
2894 return INVALID_POSITION;
2895 }
2896
2897 /**
2898 * Do an arrow scroll based on focus searching. If a new view is
2899 * given focus, return the selection delta and amount to scroll via
2900 * an {@link ArrowScrollFocusResult}, otherwise, return null.
2901 *
2902 * @param direction either {@link android.view.View#FOCUS_UP} or
2903 * {@link android.view.View#FOCUS_DOWN}.
2904 * @return The result if focus has changed, or <code>null</code>.
2905 */
2906 private ArrowScrollFocusResult arrowScrollFocused(final int direction) {
2907 final View selectedView = getSelectedView();
2908 View newFocus;
2909 if (selectedView != null && selectedView.hasFocus()) {
2910 View oldFocus = selectedView.findFocus();
2911 newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction);
2912 } else {
2913 if (direction == View.FOCUS_DOWN) {
2914 final boolean topFadingEdgeShowing = (mFirstPosition > 0);
2915 final int listTop = mListPadding.top +
2916 (topFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2917 final int ySearchPoint =
2918 (selectedView != null && selectedView.getTop() > listTop) ?
2919 selectedView.getTop() :
2920 listTop;
2921 mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2922 } else {
2923 final boolean bottomFadingEdgeShowing =
2924 (mFirstPosition + getChildCount() - 1) < mItemCount;
2925 final int listBottom = getHeight() - mListPadding.bottom -
2926 (bottomFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2927 final int ySearchPoint =
2928 (selectedView != null && selectedView.getBottom() < listBottom) ?
2929 selectedView.getBottom() :
2930 listBottom;
2931 mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2932 }
2933 newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, mTempRect, direction);
2934 }
2935
2936 if (newFocus != null) {
2937 final int positionOfNewFocus = positionOfNewFocus(newFocus);
2938
2939 // if the focus change is in a different new position, make sure
2940 // we aren't jumping over another selectable position
2941 if (mSelectedPosition != INVALID_POSITION && positionOfNewFocus != mSelectedPosition) {
2942 final int selectablePosition = lookForSelectablePositionOnScreen(direction);
2943 if (selectablePosition != INVALID_POSITION &&
2944 ((direction == View.FOCUS_DOWN && selectablePosition < positionOfNewFocus) ||
2945 (direction == View.FOCUS_UP && selectablePosition > positionOfNewFocus))) {
2946 return null;
2947 }
2948 }
2949
2950 int focusScroll = amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus);
2951
2952 final int maxScrollAmount = getMaxScrollAmount();
2953 if (focusScroll < maxScrollAmount) {
2954 // not moving too far, safe to give next view focus
2955 newFocus.requestFocus(direction);
2956 mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll);
2957 return mArrowScrollFocusResult;
2958 } else if (distanceToView(newFocus) < maxScrollAmount){
2959 // Case to consider:
2960 // too far to get entire next focusable on screen, but by going
2961 // max scroll amount, we are getting it at least partially in view,
2962 // so give it focus and scroll the max ammount.
2963 newFocus.requestFocus(direction);
2964 mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount);
2965 return mArrowScrollFocusResult;
2966 }
2967 }
2968 return null;
2969 }
2970
2971 /**
2972 * @param newFocus The view that would have focus.
2973 * @return the position that contains newFocus
2974 */
2975 private int positionOfNewFocus(View newFocus) {
2976 final int numChildren = getChildCount();
2977 for (int i = 0; i < numChildren; i++) {
2978 final View child = getChildAt(i);
2979 if (isViewAncestorOf(newFocus, child)) {
2980 return mFirstPosition + i;
2981 }
2982 }
2983 throw new IllegalArgumentException("newFocus is not a child of any of the"
2984 + " children of the list!");
2985 }
2986
2987 /**
2988 * Return true if child is an ancestor of parent, (or equal to the parent).
2989 */
2990 private boolean isViewAncestorOf(View child, View parent) {
2991 if (child == parent) {
2992 return true;
2993 }
2994
2995 final ViewParent theParent = child.getParent();
2996 return (theParent instanceof ViewGroup) && isViewAncestorOf((View) theParent, parent);
2997 }
2998
2999 /**
3000 * Determine how much we need to scroll in order to get newFocus in view.
3001 * @param direction either {@link android.view.View#FOCUS_UP} or
3002 * {@link android.view.View#FOCUS_DOWN}.
3003 * @param newFocus The view that would take focus.
3004 * @param positionOfNewFocus The position of the list item containing newFocus
3005 * @return The amount to scroll. Note: this is always positive! Direction
3006 * needs to be taken into account when actually scrolling.
3007 */
3008 private int amountToScrollToNewFocus(int direction, View newFocus, int positionOfNewFocus) {
3009 int amountToScroll = 0;
3010 newFocus.getDrawingRect(mTempRect);
3011 offsetDescendantRectToMyCoords(newFocus, mTempRect);
3012 if (direction == View.FOCUS_UP) {
3013 if (mTempRect.top < mListPadding.top) {
3014 amountToScroll = mListPadding.top - mTempRect.top;
3015 if (positionOfNewFocus > 0) {
3016 amountToScroll += getArrowScrollPreviewLength();
3017 }
3018 }
3019 } else {
3020 final int listBottom = getHeight() - mListPadding.bottom;
3021 if (mTempRect.bottom > listBottom) {
3022 amountToScroll = mTempRect.bottom - listBottom;
3023 if (positionOfNewFocus < mItemCount - 1) {
3024 amountToScroll += getArrowScrollPreviewLength();
3025 }
3026 }
3027 }
3028 return amountToScroll;
3029 }
3030
3031 /**
3032 * Determine the distance to the nearest edge of a view in a particular
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08003033 * direction.
3034 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 * @param descendant A descendant of this list.
3036 * @return The distance, or 0 if the nearest edge is already on screen.
3037 */
3038 private int distanceToView(View descendant) {
3039 int distance = 0;
3040 descendant.getDrawingRect(mTempRect);
3041 offsetDescendantRectToMyCoords(descendant, mTempRect);
3042 final int listBottom = mBottom - mTop - mListPadding.bottom;
3043 if (mTempRect.bottom < mListPadding.top) {
3044 distance = mListPadding.top - mTempRect.bottom;
3045 } else if (mTempRect.top > listBottom) {
3046 distance = mTempRect.top - listBottom;
3047 }
3048 return distance;
3049 }
3050
3051
3052 /**
3053 * Scroll the children by amount, adding a view at the end and removing
3054 * views that fall off as necessary.
3055 *
3056 * @param amount The amount (positive or negative) to scroll.
3057 */
3058 private void scrollListItemsBy(int amount) {
3059 offsetChildrenTopAndBottom(amount);
3060
3061 final int listBottom = getHeight() - mListPadding.bottom;
3062 final int listTop = mListPadding.top;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003063 final AbsListView.RecycleBin recycleBin = mRecycler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064
3065 if (amount < 0) {
3066 // shifted items up
3067
3068 // may need to pan views into the bottom space
3069 int numChildren = getChildCount();
3070 View last = getChildAt(numChildren - 1);
3071 while (last.getBottom() < listBottom) {
3072 final int lastVisiblePosition = mFirstPosition + numChildren - 1;
3073 if (lastVisiblePosition < mItemCount - 1) {
3074 last = addViewBelow(last, lastVisiblePosition);
3075 numChildren++;
3076 } else {
3077 break;
3078 }
3079 }
3080
3081 // may have brought in the last child of the list that is skinnier
3082 // than the fading edge, thereby leaving space at the end. need
3083 // to shift back
3084 if (last.getBottom() < listBottom) {
3085 offsetChildrenTopAndBottom(listBottom - last.getBottom());
3086 }
3087
3088 // top views may be panned off screen
3089 View first = getChildAt(0);
3090 while (first.getBottom() < listTop) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003091 AbsListView.LayoutParams layoutParams = (LayoutParams) first.getLayoutParams();
3092 if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07003093 recycleBin.addScrapView(first, mFirstPosition);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003094 }
Mattias Niklewski158d6b72011-02-02 15:52:37 +01003095 detachViewFromParent(first);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 first = getChildAt(0);
3097 mFirstPosition++;
3098 }
3099 } else {
3100 // shifted items down
3101 View first = getChildAt(0);
3102
3103 // may need to pan views into top
3104 while ((first.getTop() > listTop) && (mFirstPosition > 0)) {
3105 first = addViewAbove(first, mFirstPosition);
3106 mFirstPosition--;
3107 }
3108
3109 // may have brought the very first child of the list in too far and
3110 // need to shift it back
3111 if (first.getTop() > listTop) {
3112 offsetChildrenTopAndBottom(listTop - first.getTop());
3113 }
3114
3115 int lastIndex = getChildCount() - 1;
3116 View last = getChildAt(lastIndex);
3117
3118 // bottom view may be panned off screen
3119 while (last.getTop() > listBottom) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003120 AbsListView.LayoutParams layoutParams = (LayoutParams) last.getLayoutParams();
3121 if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07003122 recycleBin.addScrapView(last, mFirstPosition+lastIndex);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003123 }
Mattias Niklewski158d6b72011-02-02 15:52:37 +01003124 detachViewFromParent(last);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 last = getChildAt(--lastIndex);
3126 }
3127 }
3128 }
3129
3130 private View addViewAbove(View theView, int position) {
3131 int abovePosition = position - 1;
Romain Guy21875052010-01-06 18:48:08 -08003132 View view = obtainView(abovePosition, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 int edgeOfNewChild = theView.getTop() - mDividerHeight;
Romain Guy21875052010-01-06 18:48:08 -08003134 setupChild(view, abovePosition, edgeOfNewChild, false, mListPadding.left,
3135 false, mIsScrap[0]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 return view;
3137 }
3138
3139 private View addViewBelow(View theView, int position) {
3140 int belowPosition = position + 1;
Romain Guy21875052010-01-06 18:48:08 -08003141 View view = obtainView(belowPosition, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 int edgeOfNewChild = theView.getBottom() + mDividerHeight;
Romain Guy21875052010-01-06 18:48:08 -08003143 setupChild(view, belowPosition, edgeOfNewChild, true, mListPadding.left,
3144 false, mIsScrap[0]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 return view;
3146 }
3147
3148 /**
3149 * Indicates that the views created by the ListAdapter can contain focusable
3150 * items.
3151 *
3152 * @param itemsCanFocus true if items can get focus, false otherwise
3153 */
3154 public void setItemsCanFocus(boolean itemsCanFocus) {
3155 mItemsCanFocus = itemsCanFocus;
3156 if (!itemsCanFocus) {
3157 setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
3158 }
3159 }
3160
3161 /**
3162 * @return Whether the views created by the ListAdapter can contain focusable
3163 * items.
3164 */
3165 public boolean getItemsCanFocus() {
3166 return mItemsCanFocus;
3167 }
3168
3169 @Override
Romain Guy24443ea2009-05-11 11:56:30 -07003170 public boolean isOpaque() {
Chet Haase78400552011-03-03 08:18:17 -08003171 boolean retValue = (mCachingActive && mIsCacheColorOpaque && mDividerIsOpaque &&
Romain Guy8f1344f52009-05-15 16:03:59 -07003172 hasOpaqueScrollbars()) || super.isOpaque();
Chet Haase78400552011-03-03 08:18:17 -08003173 if (retValue) {
3174 // only return true if the list items cover the entire area of the view
Adam Powell3ba8f5d62011-03-07 15:36:33 -08003175 final int listTop = mListPadding != null ? mListPadding.top : mPaddingTop;
Chet Haase78400552011-03-03 08:18:17 -08003176 View first = getChildAt(0);
3177 if (first == null || first.getTop() > listTop) {
3178 return false;
3179 }
Adam Powell3ba8f5d62011-03-07 15:36:33 -08003180 final int listBottom = getHeight() -
3181 (mListPadding != null ? mListPadding.bottom : mPaddingBottom);
Chet Haase78400552011-03-03 08:18:17 -08003182 View last = getChildAt(getChildCount() - 1);
3183 if (last == null || last.getBottom() < listBottom) {
3184 return false;
3185 }
3186 }
3187 return retValue;
Romain Guy24443ea2009-05-11 11:56:30 -07003188 }
3189
3190 @Override
3191 public void setCacheColorHint(int color) {
Romain Guy8f1344f52009-05-15 16:03:59 -07003192 final boolean opaque = (color >>> 24) == 0xFF;
3193 mIsCacheColorOpaque = opaque;
3194 if (opaque) {
Romain Guya02903f2009-05-23 13:26:46 -07003195 if (mDividerPaint == null) {
3196 mDividerPaint = new Paint();
3197 }
Romain Guy8f1344f52009-05-15 16:03:59 -07003198 mDividerPaint.setColor(color);
3199 }
Romain Guy24443ea2009-05-11 11:56:30 -07003200 super.setCacheColorHint(color);
3201 }
Adam Powell637d3372010-08-25 14:37:03 -07003202
3203 void drawOverscrollHeader(Canvas canvas, Drawable drawable, Rect bounds) {
3204 final int height = drawable.getMinimumHeight();
3205
3206 canvas.save();
3207 canvas.clipRect(bounds);
3208
3209 final int span = bounds.bottom - bounds.top;
3210 if (span < height) {
3211 bounds.top = bounds.bottom - height;
3212 }
3213
3214 drawable.setBounds(bounds);
3215 drawable.draw(canvas);
3216
3217 canvas.restore();
3218 }
3219
3220 void drawOverscrollFooter(Canvas canvas, Drawable drawable, Rect bounds) {
3221 final int height = drawable.getMinimumHeight();
3222
3223 canvas.save();
3224 canvas.clipRect(bounds);
3225
3226 final int span = bounds.bottom - bounds.top;
3227 if (span < height) {
3228 bounds.bottom = bounds.top + height;
3229 }
3230
3231 drawable.setBounds(bounds);
3232 drawable.draw(canvas);
3233
3234 canvas.restore();
3235 }
3236
Romain Guy24443ea2009-05-11 11:56:30 -07003237 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003238 protected void dispatchDraw(Canvas canvas) {
Romain Guy0211a0a2011-02-14 16:34:59 -08003239 if (mCachingStarted) {
3240 mCachingActive = true;
3241 }
3242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 // Draw the dividers
3244 final int dividerHeight = mDividerHeight;
Adam Powell637d3372010-08-25 14:37:03 -07003245 final Drawable overscrollHeader = mOverScrollHeader;
3246 final Drawable overscrollFooter = mOverScrollFooter;
3247 final boolean drawOverscrollHeader = overscrollHeader != null;
3248 final boolean drawOverscrollFooter = overscrollFooter != null;
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003249 final boolean drawDividers = dividerHeight > 0 && mDivider != null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250
Adam Powell637d3372010-08-25 14:37:03 -07003251 if (drawDividers || drawOverscrollHeader || drawOverscrollFooter) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 // Only modify the top and bottom in the loop, we set the left and right here
3253 final Rect bounds = mTempRect;
3254 bounds.left = mPaddingLeft;
3255 bounds.right = mRight - mLeft - mPaddingRight;
3256
3257 final int count = getChildCount();
3258 final int headerCount = mHeaderViewInfos.size();
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003259 final int itemCount = mItemCount;
Alan Viveretteb9fc4b82013-06-03 16:42:22 -07003260 final int footerLimit = (itemCount - mFooterViewInfos.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 final boolean headerDividers = mHeaderDividersEnabled;
3262 final boolean footerDividers = mFooterDividersEnabled;
3263 final int first = mFirstPosition;
Romain Guy2bed2272009-03-24 18:23:21 -07003264 final boolean areAllItemsSelectable = mAreAllItemsSelectable;
3265 final ListAdapter adapter = mAdapter;
Romain Guye32edc62009-05-29 10:33:36 -07003266 // If the list is opaque *and* the background is not, we want to
3267 // fill a rect where the dividers would be for non-selectable items
3268 // If the list is opaque and the background is also opaque, we don't
3269 // need to draw anything since the background will do it for us
Romain Guy179de8a2010-07-09 13:27:00 -07003270 final boolean fillForMissingDividers = isOpaque() && !super.isOpaque();
Romain Guye32edc62009-05-29 10:33:36 -07003271
3272 if (fillForMissingDividers && mDividerPaint == null && mIsCacheColorOpaque) {
Romain Guya02903f2009-05-23 13:26:46 -07003273 mDividerPaint = new Paint();
Romain Guye32edc62009-05-29 10:33:36 -07003274 mDividerPaint.setColor(getCacheColorHint());
Romain Guya02903f2009-05-23 13:26:46 -07003275 }
Romain Guy8f1344f52009-05-15 16:03:59 -07003276 final Paint paint = mDividerPaint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277
Adam Powell94566552011-01-05 23:25:33 -08003278 int effectivePaddingTop = 0;
3279 int effectivePaddingBottom = 0;
3280 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
3281 effectivePaddingTop = mListPadding.top;
3282 effectivePaddingBottom = mListPadding.bottom;
3283 }
3284
3285 final int listBottom = mBottom - mTop - effectivePaddingBottom + mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 if (!mStackFromBottom) {
Adam Powell637d3372010-08-25 14:37:03 -07003287 int bottom = 0;
Adam Powell0b8bb422010-02-08 14:30:45 -08003288
Adam Powell637d3372010-08-25 14:37:03 -07003289 // Draw top divider or header for overscroll
3290 final int scrollY = mScrollY;
3291 if (count > 0 && scrollY < 0) {
3292 if (drawOverscrollHeader) {
3293 bounds.bottom = 0;
3294 bounds.top = scrollY;
3295 drawOverscrollHeader(canvas, overscrollHeader, bounds);
3296 } else if (drawDividers) {
3297 bounds.bottom = 0;
3298 bounds.top = -dividerHeight;
3299 drawDivider(canvas, bounds, -1);
3300 }
3301 }
3302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 for (int i = 0; i < count; i++) {
Alan Viveretteb9fc4b82013-06-03 16:42:22 -07003304 final int itemIndex = (first + i);
3305 final boolean isHeader = (itemIndex < headerCount);
3306 final boolean isFooter = (itemIndex >= footerLimit);
3307 if ((headerDividers || !isHeader) && (footerDividers || !isFooter)) {
3308 final View child = getChildAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 bottom = child.getBottom();
Alan Viveretteb9fc4b82013-06-03 16:42:22 -07003310 final boolean isLastItem = (i == (count - 1));
Adam Powell637d3372010-08-25 14:37:03 -07003311
Alan Viveretteb9fc4b82013-06-03 16:42:22 -07003312 if (drawDividers && (bottom < listBottom)
3313 && !(drawOverscrollFooter && isLastItem)) {
3314 final int nextIndex = (itemIndex + 1);
Alan Viverette20cc6052013-11-15 15:56:38 -08003315 // Draw dividers between enabled items, headers
3316 // and/or footers when enabled and requested, and
3317 // after the last enabled item.
3318 if (adapter.isEnabled(itemIndex) && (headerDividers || !isHeader
3319 && (nextIndex >= headerCount)) && (isLastItem
3320 || adapter.isEnabled(nextIndex) && (footerDividers || !isFooter
3321 && (nextIndex < footerLimit)))) {
Adam Powell637d3372010-08-25 14:37:03 -07003322 bounds.top = bottom;
3323 bounds.bottom = bottom + dividerHeight;
3324 drawDivider(canvas, bounds, i);
3325 } else if (fillForMissingDividers) {
3326 bounds.top = bottom;
3327 bounds.bottom = bottom + dividerHeight;
3328 canvas.drawRect(bounds, paint);
3329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 }
3331 }
3332 }
Adam Powell637d3372010-08-25 14:37:03 -07003333
3334 final int overFooterBottom = mBottom + mScrollY;
3335 if (drawOverscrollFooter && first + count == itemCount &&
3336 overFooterBottom > bottom) {
3337 bounds.top = bottom;
3338 bounds.bottom = overFooterBottom;
3339 drawOverscrollFooter(canvas, overscrollFooter, bounds);
3340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 } else {
3342 int top;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003344 final int scrollY = mScrollY;
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003345
Adam Powell637d3372010-08-25 14:37:03 -07003346 if (count > 0 && drawOverscrollHeader) {
3347 bounds.top = scrollY;
3348 bounds.bottom = getChildAt(0).getTop();
3349 drawOverscrollHeader(canvas, overscrollHeader, bounds);
3350 }
3351
3352 final int start = drawOverscrollHeader ? 1 : 0;
3353 for (int i = start; i < count; i++) {
Alan Viveretteb9fc4b82013-06-03 16:42:22 -07003354 final int itemIndex = (first + i);
3355 final boolean isHeader = (itemIndex < headerCount);
3356 final boolean isFooter = (itemIndex >= footerLimit);
3357 if ((headerDividers || !isHeader) && (footerDividers || !isFooter)) {
3358 final View child = getChildAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 top = child.getTop();
Alan Viveretteb9fc4b82013-06-03 16:42:22 -07003360 if (drawDividers && (top > effectivePaddingTop)) {
3361 final boolean isFirstItem = (i == start);
3362 final int previousIndex = (itemIndex - 1);
Alan Viverette20cc6052013-11-15 15:56:38 -08003363 // Draw dividers between enabled items, headers
3364 // and/or footers when enabled and requested, and
3365 // before the first enabled item.
3366 if (adapter.isEnabled(itemIndex) && (headerDividers || !isHeader
3367 && (previousIndex >= headerCount)) && (isFirstItem ||
3368 adapter.isEnabled(previousIndex) && (footerDividers || !isFooter
3369 && (previousIndex < footerLimit)))) {
Romain Guy8f1344f52009-05-15 16:03:59 -07003370 bounds.top = top - dividerHeight;
3371 bounds.bottom = top;
Alan Viveretteb9fc4b82013-06-03 16:42:22 -07003372 // Give the method the child ABOVE the divider,
3373 // so we subtract one from our child position.
3374 // Give -1 when there is no child above the
Romain Guy8f1344f52009-05-15 16:03:59 -07003375 // divider.
3376 drawDivider(canvas, bounds, i - 1);
Romain Guye32edc62009-05-29 10:33:36 -07003377 } else if (fillForMissingDividers) {
Romain Guy8f1344f52009-05-15 16:03:59 -07003378 bounds.top = top - dividerHeight;
3379 bounds.bottom = top;
3380 canvas.drawRect(bounds, paint);
3381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 }
3383 }
3384 }
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003385
Romain Guy179de8a2010-07-09 13:27:00 -07003386 if (count > 0 && scrollY > 0) {
Adam Powell637d3372010-08-25 14:37:03 -07003387 if (drawOverscrollFooter) {
3388 final int absListBottom = mBottom;
3389 bounds.top = absListBottom;
3390 bounds.bottom = absListBottom + scrollY;
3391 drawOverscrollFooter(canvas, overscrollFooter, bounds);
3392 } else if (drawDividers) {
3393 bounds.top = listBottom;
3394 bounds.bottom = listBottom + dividerHeight;
3395 drawDivider(canvas, bounds, -1);
3396 }
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
3399 }
3400
3401 // Draw the indicators (these should be drawn above the dividers) and children
3402 super.dispatchDraw(canvas);
3403 }
3404
Romain Guy0211a0a2011-02-14 16:34:59 -08003405 @Override
3406 protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3407 boolean more = super.drawChild(canvas, child, drawingTime);
3408 if (mCachingActive && child.mCachingFailed) {
3409 mCachingActive = false;
3410 }
3411 return more;
3412 }
3413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 /**
3415 * Draws a divider for the given child in the given bounds.
3416 *
3417 * @param canvas The canvas to draw to.
3418 * @param bounds The bounds of the divider.
3419 * @param childIndex The index of child (of the View) above the divider.
3420 * This will be -1 if there is no child above the divider to be
3421 * drawn.
3422 */
3423 void drawDivider(Canvas canvas, Rect bounds, int childIndex) {
3424 // This widget draws the same divider for all children
3425 final Drawable divider = mDivider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426
Romain Guy95930e12010-10-04 13:46:02 -07003427 divider.setBounds(bounds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 divider.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 }
3430
3431 /**
3432 * Returns the drawable that will be drawn between each item in the list.
3433 *
3434 * @return the current drawable drawn between list elements
3435 */
3436 public Drawable getDivider() {
3437 return mDivider;
3438 }
3439
3440 /**
3441 * Sets the drawable that will be drawn between each item in the list. If the drawable does
3442 * not have an intrinsic height, you should also call {@link #setDividerHeight(int)}
3443 *
3444 * @param divider The drawable to use.
3445 */
3446 public void setDivider(Drawable divider) {
3447 if (divider != null) {
3448 mDividerHeight = divider.getIntrinsicHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 } else {
3450 mDividerHeight = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 }
3452 mDivider = divider;
Romain Guy24443ea2009-05-11 11:56:30 -07003453 mDividerIsOpaque = divider == null || divider.getOpacity() == PixelFormat.OPAQUE;
Romain Guyeeb55e62010-12-01 18:46:07 -08003454 requestLayout();
3455 invalidate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 }
3457
3458 /**
3459 * @return Returns the height of the divider that will be drawn between each item in the list.
3460 */
3461 public int getDividerHeight() {
3462 return mDividerHeight;
3463 }
3464
3465 /**
3466 * Sets the height of the divider that will be drawn between each item in the list. Calling
3467 * this will override the intrinsic height as set by {@link #setDivider(Drawable)}
3468 *
3469 * @param height The new height of the divider in pixels.
3470 */
3471 public void setDividerHeight(int height) {
3472 mDividerHeight = height;
Romain Guyeeb55e62010-12-01 18:46:07 -08003473 requestLayout();
3474 invalidate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 }
3476
3477 /**
3478 * Enables or disables the drawing of the divider for header views.
3479 *
3480 * @param headerDividersEnabled True to draw the headers, false otherwise.
3481 *
3482 * @see #setFooterDividersEnabled(boolean)
Alan Viverette55421032013-06-11 17:50:56 -07003483 * @see #areHeaderDividersEnabled()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 * @see #addHeaderView(android.view.View)
3485 */
3486 public void setHeaderDividersEnabled(boolean headerDividersEnabled) {
3487 mHeaderDividersEnabled = headerDividersEnabled;
3488 invalidate();
3489 }
3490
3491 /**
Alan Viverette55421032013-06-11 17:50:56 -07003492 * @return Whether the drawing of the divider for header views is enabled
3493 *
3494 * @see #setHeaderDividersEnabled(boolean)
3495 */
3496 public boolean areHeaderDividersEnabled() {
3497 return mHeaderDividersEnabled;
3498 }
3499
3500 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 * Enables or disables the drawing of the divider for footer views.
3502 *
3503 * @param footerDividersEnabled True to draw the footers, false otherwise.
3504 *
3505 * @see #setHeaderDividersEnabled(boolean)
Alan Viverette55421032013-06-11 17:50:56 -07003506 * @see #areFooterDividersEnabled()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 * @see #addFooterView(android.view.View)
3508 */
3509 public void setFooterDividersEnabled(boolean footerDividersEnabled) {
3510 mFooterDividersEnabled = footerDividersEnabled;
3511 invalidate();
3512 }
Alan Viverette55421032013-06-11 17:50:56 -07003513
3514 /**
3515 * @return Whether the drawing of the divider for footer views is enabled
3516 *
3517 * @see #setFooterDividersEnabled(boolean)
3518 */
3519 public boolean areFooterDividersEnabled() {
3520 return mFooterDividersEnabled;
3521 }
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003522
Adam Powell637d3372010-08-25 14:37:03 -07003523 /**
3524 * Sets the drawable that will be drawn above all other list content.
3525 * This area can become visible when the user overscrolls the list.
3526 *
3527 * @param header The drawable to use
3528 */
3529 public void setOverscrollHeader(Drawable header) {
3530 mOverScrollHeader = header;
3531 if (mScrollY < 0) {
3532 invalidate();
3533 }
3534 }
3535
3536 /**
3537 * @return The drawable that will be drawn above all other list content
3538 */
3539 public Drawable getOverscrollHeader() {
3540 return mOverScrollHeader;
3541 }
3542
3543 /**
3544 * Sets the drawable that will be drawn below all other list content.
3545 * This area can become visible when the user overscrolls the list,
3546 * or when the list's content does not fully fill the container area.
3547 *
3548 * @param footer The drawable to use
3549 */
3550 public void setOverscrollFooter(Drawable footer) {
3551 mOverScrollFooter = footer;
3552 invalidate();
3553 }
3554
3555 /**
3556 * @return The drawable that will be drawn below all other list content
3557 */
3558 public Drawable getOverscrollFooter() {
3559 return mOverScrollFooter;
3560 }
3561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 @Override
3563 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3564 super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
3565
Adam Powelle1bf4862011-09-02 16:56:20 -07003566 final ListAdapter adapter = mAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 int closetChildIndex = -1;
Adam Powelldcce1212011-10-31 16:41:21 -07003568 int closestChildTop = 0;
Adam Powelle1bf4862011-09-02 16:56:20 -07003569 if (adapter != null && gainFocus && previouslyFocusedRect != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 previouslyFocusedRect.offset(mScrollX, mScrollY);
3571
Adam Powelld7507832010-02-18 15:40:33 -08003572 // Don't cache the result of getChildCount or mFirstPosition here,
3573 // it could change in layoutChildren.
3574 if (adapter.getCount() < getChildCount() + mFirstPosition) {
Adam Powellc854f282009-12-16 14:11:53 -08003575 mLayoutMode = LAYOUT_NORMAL;
3576 layoutChildren();
3577 }
3578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 // figure out which item should be selected based on previously
3580 // focused rect
3581 Rect otherRect = mTempRect;
3582 int minDistance = Integer.MAX_VALUE;
3583 final int childCount = getChildCount();
Adam Powelld7507832010-02-18 15:40:33 -08003584 final int firstPosition = mFirstPosition;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585
3586 for (int i = 0; i < childCount; i++) {
3587 // only consider selectable views
3588 if (!adapter.isEnabled(firstPosition + i)) {
3589 continue;
3590 }
3591
3592 View other = getChildAt(i);
3593 other.getDrawingRect(otherRect);
3594 offsetDescendantRectToMyCoords(other, otherRect);
3595 int distance = getDistance(previouslyFocusedRect, otherRect, direction);
3596
3597 if (distance < minDistance) {
3598 minDistance = distance;
3599 closetChildIndex = i;
Adam Powelldcce1212011-10-31 16:41:21 -07003600 closestChildTop = other.getTop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 }
3602 }
3603 }
3604
3605 if (closetChildIndex >= 0) {
Adam Powelldcce1212011-10-31 16:41:21 -07003606 setSelectionFromTop(closetChildIndex + mFirstPosition, closestChildTop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 } else {
3608 requestLayout();
3609 }
3610 }
3611
3612
3613 /*
3614 * (non-Javadoc)
3615 *
3616 * Children specified in XML are assumed to be header views. After we have
3617 * parsed them move them out of the children list and into mHeaderViews.
3618 */
3619 @Override
3620 protected void onFinishInflate() {
3621 super.onFinishInflate();
3622
3623 int count = getChildCount();
3624 if (count > 0) {
3625 for (int i = 0; i < count; ++i) {
3626 addHeaderView(getChildAt(i));
3627 }
3628 removeAllViews();
3629 }
3630 }
3631
3632 /* (non-Javadoc)
3633 * @see android.view.View#findViewById(int)
3634 * First look in our children, then in any header and footer views that may be scrolled off.
3635 */
3636 @Override
Tor Norbye7b9c9122013-05-30 16:48:33 -07003637 protected View findViewTraversal(@IdRes int id) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 View v;
3639 v = super.findViewTraversal(id);
3640 if (v == null) {
3641 v = findViewInHeadersOrFooters(mHeaderViewInfos, id);
3642 if (v != null) {
3643 return v;
3644 }
3645 v = findViewInHeadersOrFooters(mFooterViewInfos, id);
3646 if (v != null) {
3647 return v;
3648 }
3649 }
3650 return v;
3651 }
3652
3653 /* (non-Javadoc)
3654 *
3655 * Look in the passed in list of headers or footers for the view.
3656 */
3657 View findViewInHeadersOrFooters(ArrayList<FixedViewInfo> where, int id) {
3658 if (where != null) {
3659 int len = where.size();
3660 View v;
3661
3662 for (int i = 0; i < len; i++) {
3663 v = where.get(i).view;
3664
3665 if (!v.isRootNamespace()) {
3666 v = v.findViewById(id);
3667
3668 if (v != null) {
3669 return v;
3670 }
3671 }
3672 }
3673 }
3674 return null;
3675 }
3676
3677 /* (non-Javadoc)
Jeff Brown4e6319b2010-12-13 10:36:51 -08003678 * @see android.view.View#findViewWithTag(Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 * First look in our children, then in any header and footer views that may be scrolled off.
3680 */
3681 @Override
3682 protected View findViewWithTagTraversal(Object tag) {
3683 View v;
3684 v = super.findViewWithTagTraversal(tag);
3685 if (v == null) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08003686 v = findViewWithTagInHeadersOrFooters(mHeaderViewInfos, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 if (v != null) {
3688 return v;
3689 }
3690
Jeff Brown4e6319b2010-12-13 10:36:51 -08003691 v = findViewWithTagInHeadersOrFooters(mFooterViewInfos, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 if (v != null) {
3693 return v;
3694 }
3695 }
3696 return v;
3697 }
3698
3699 /* (non-Javadoc)
3700 *
3701 * Look in the passed in list of headers or footers for the view with the tag.
3702 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08003703 View findViewWithTagInHeadersOrFooters(ArrayList<FixedViewInfo> where, Object tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 if (where != null) {
3705 int len = where.size();
3706 View v;
3707
3708 for (int i = 0; i < len; i++) {
3709 v = where.get(i).view;
3710
3711 if (!v.isRootNamespace()) {
3712 v = v.findViewWithTag(tag);
3713
3714 if (v != null) {
3715 return v;
3716 }
3717 }
3718 }
3719 }
3720 return null;
3721 }
3722
Jeff Brown4e6319b2010-12-13 10:36:51 -08003723 /**
3724 * @hide
3725 * @see android.view.View#findViewByPredicate(Predicate)
3726 * First look in our children, then in any header and footer views that may be scrolled off.
3727 */
3728 @Override
Jeff Brown4dfbec22011-08-15 14:55:37 -07003729 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08003730 View v;
Jeff Brown4dfbec22011-08-15 14:55:37 -07003731 v = super.findViewByPredicateTraversal(predicate, childToSkip);
Jeff Brown4e6319b2010-12-13 10:36:51 -08003732 if (v == null) {
Jeff Brown4dfbec22011-08-15 14:55:37 -07003733 v = findViewByPredicateInHeadersOrFooters(mHeaderViewInfos, predicate, childToSkip);
Jeff Brown4e6319b2010-12-13 10:36:51 -08003734 if (v != null) {
3735 return v;
3736 }
3737
Jeff Brown4dfbec22011-08-15 14:55:37 -07003738 v = findViewByPredicateInHeadersOrFooters(mFooterViewInfos, predicate, childToSkip);
Jeff Brown4e6319b2010-12-13 10:36:51 -08003739 if (v != null) {
3740 return v;
3741 }
3742 }
3743 return v;
3744 }
3745
3746 /* (non-Javadoc)
3747 *
3748 * Look in the passed in list of headers or footers for the first view that matches
3749 * the predicate.
3750 */
3751 View findViewByPredicateInHeadersOrFooters(ArrayList<FixedViewInfo> where,
Jeff Brown4dfbec22011-08-15 14:55:37 -07003752 Predicate<View> predicate, View childToSkip) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08003753 if (where != null) {
3754 int len = where.size();
3755 View v;
3756
3757 for (int i = 0; i < len; i++) {
3758 v = where.get(i).view;
3759
Jeff Brown4dfbec22011-08-15 14:55:37 -07003760 if (v != childToSkip && !v.isRootNamespace()) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08003761 v = v.findViewByPredicate(predicate);
3762
3763 if (v != null) {
3764 return v;
3765 }
3766 }
3767 }
3768 }
3769 return null;
3770 }
3771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 /**
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08003773 * Returns the set of checked items ids. The result is only valid if the
Adam Powell8f1bfe12010-03-05 15:13:56 -08003774 * choice mode has not been set to {@link #CHOICE_MODE_NONE}.
3775 *
3776 * @return A new array which contains the id of each checked item in the
3777 * list.
3778 *
Adam Powell463ceff2010-03-09 11:50:51 -08003779 * @deprecated Use {@link #getCheckedItemIds()} instead.
Adam Powell8f1bfe12010-03-05 15:13:56 -08003780 */
Adam Powell8350f7d2010-07-28 14:27:28 -07003781 @Deprecated
Adam Powell8f1bfe12010-03-05 15:13:56 -08003782 public long[] getCheckItemIds() {
Adam Powell463ceff2010-03-09 11:50:51 -08003783 // Use new behavior that correctly handles stable ID mapping.
3784 if (mAdapter != null && mAdapter.hasStableIds()) {
3785 return getCheckedItemIds();
3786 }
3787
3788 // Old behavior was buggy, but would sort of work for adapters without stable IDs.
3789 // Fall back to it to support legacy apps.
3790 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null && mAdapter != null) {
3791 final SparseBooleanArray states = mCheckStates;
3792 final int count = states.size();
3793 final long[] ids = new long[count];
3794 final ListAdapter adapter = mAdapter;
3795
3796 int checkedCount = 0;
3797 for (int i = 0; i < count; i++) {
3798 if (states.valueAt(i)) {
3799 ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
3800 }
3801 }
3802
3803 // Trim array if needed. mCheckStates may contain false values
3804 // resulting in checkedCount being smaller than count.
3805 if (checkedCount == count) {
3806 return ids;
3807 } else {
3808 final long[] result = new long[checkedCount];
3809 System.arraycopy(ids, 0, result, 0, checkedCount);
3810
3811 return result;
3812 }
3813 }
3814 return new long[0];
Adam Powell8f1bfe12010-03-05 15:13:56 -08003815 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08003816
3817 @Override
Alan Viverette441b4372014-02-12 13:30:20 -08003818 int getHeightForPosition(int position) {
3819 final int height = super.getHeightForPosition(position);
3820 if (shouldAdjustHeightForDivider(position)) {
3821 return height + mDividerHeight;
3822 }
3823 return height;
3824 }
3825
3826 private boolean shouldAdjustHeightForDivider(int itemIndex) {
3827 final int dividerHeight = mDividerHeight;
3828 final Drawable overscrollHeader = mOverScrollHeader;
3829 final Drawable overscrollFooter = mOverScrollFooter;
3830 final boolean drawOverscrollHeader = overscrollHeader != null;
3831 final boolean drawOverscrollFooter = overscrollFooter != null;
3832 final boolean drawDividers = dividerHeight > 0 && mDivider != null;
3833
3834 if (drawDividers) {
3835 final boolean fillForMissingDividers = isOpaque() && !super.isOpaque();
3836 final int itemCount = mItemCount;
3837 final int headerCount = mHeaderViewInfos.size();
3838 final int footerLimit = (itemCount - mFooterViewInfos.size());
3839 final boolean isHeader = (itemIndex < headerCount);
3840 final boolean isFooter = (itemIndex >= footerLimit);
3841 final boolean headerDividers = mHeaderDividersEnabled;
3842 final boolean footerDividers = mFooterDividersEnabled;
3843 if ((headerDividers || !isHeader) && (footerDividers || !isFooter)) {
3844 final ListAdapter adapter = mAdapter;
3845 if (!mStackFromBottom) {
3846 final boolean isLastItem = (itemIndex == (itemCount - 1));
3847 if (!drawOverscrollFooter || !isLastItem) {
3848 final int nextIndex = itemIndex + 1;
3849 // Draw dividers between enabled items, headers
3850 // and/or footers when enabled and requested, and
3851 // after the last enabled item.
3852 if (adapter.isEnabled(itemIndex) && (headerDividers || !isHeader
3853 && (nextIndex >= headerCount)) && (isLastItem
3854 || adapter.isEnabled(nextIndex) && (footerDividers || !isFooter
3855 && (nextIndex < footerLimit)))) {
3856 return true;
3857 } else if (fillForMissingDividers) {
3858 return true;
3859 }
3860 }
3861 } else {
3862 final int start = drawOverscrollHeader ? 1 : 0;
3863 final boolean isFirstItem = (itemIndex == start);
3864 if (!isFirstItem) {
3865 final int previousIndex = (itemIndex - 1);
3866 // Draw dividers between enabled items, headers
3867 // and/or footers when enabled and requested, and
3868 // before the first enabled item.
3869 if (adapter.isEnabled(itemIndex) && (headerDividers || !isHeader
3870 && (previousIndex >= headerCount)) && (isFirstItem ||
3871 adapter.isEnabled(previousIndex) && (footerDividers || !isFooter
3872 && (previousIndex < footerLimit)))) {
3873 return true;
3874 } else if (fillForMissingDividers) {
3875 return true;
3876 }
3877 }
3878 }
3879 }
3880 }
3881
3882 return false;
3883 }
3884
3885 @Override
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -08003886 public CharSequence getAccessibilityClassName() {
3887 return ListView.class.getName();
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08003888 }
3889
Alan Viverettea54956a2015-01-07 16:05:02 -08003890 /** @hide */
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08003891 @Override
Alan Viverettea54956a2015-01-07 16:05:02 -08003892 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
3893 super.onInitializeAccessibilityNodeInfoInternal(info);
Alan Viverette5b2081d2013-08-28 10:43:07 -07003894
Alan Viverette77c180a2014-09-08 15:30:34 -07003895 final int rowsCount = getCount();
Alan Viverette76769ae2014-02-12 16:38:10 -08003896 final int selectionMode = getSelectionModeForAccessibility();
Alan Viverette77c180a2014-09-08 15:30:34 -07003897 final CollectionInfo collectionInfo = CollectionInfo.obtain(
3898 rowsCount, 1, false, selectionMode);
Alan Viverette5b2081d2013-08-28 10:43:07 -07003899 info.setCollectionInfo(collectionInfo);
Alan Viverette23f44322015-04-06 16:04:56 -07003900
3901 if (rowsCount > 0) {
3902 info.addAction(AccessibilityAction.ACTION_SCROLL_TO_POSITION);
3903 }
3904 }
3905
3906 /** @hide */
3907 @Override
3908 public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
3909 if (super.performAccessibilityActionInternal(action, arguments)) {
3910 return true;
3911 }
3912
3913 switch (action) {
3914 case R.id.accessibilityActionScrollToPosition: {
3915 final int row = arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_ROW_INT, -1);
3916 final int position = Math.min(row, getCount() - 1);
3917 if (row >= 0) {
3918 // The accessibility service gets data asynchronously, so
3919 // we'll be a little lenient by clamping the last position.
3920 smoothScrollToPosition(position);
3921 return true;
3922 }
3923 } break;
3924 }
3925
3926 return false;
Alan Viverette5b2081d2013-08-28 10:43:07 -07003927 }
3928
3929 @Override
3930 public void onInitializeAccessibilityNodeInfoForItem(
3931 View view, int position, AccessibilityNodeInfo info) {
3932 super.onInitializeAccessibilityNodeInfoForItem(view, position, info);
3933
3934 final LayoutParams lp = (LayoutParams) view.getLayoutParams();
3935 final boolean isHeading = lp != null && lp.viewType != ITEM_VIEW_TYPE_HEADER_OR_FOOTER;
Alan Viverette76769ae2014-02-12 16:38:10 -08003936 final boolean isSelected = isItemChecked(position);
3937 final CollectionItemInfo itemInfo = CollectionItemInfo.obtain(
Alan Viverette77c180a2014-09-08 15:30:34 -07003938 position, 1, 0, 1, isHeading, isSelected);
Alan Viverette5b2081d2013-08-28 10:43:07 -07003939 info.setCollectionItemInfo(itemInfo);
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08003940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941}