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