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