// 保存当前第一个可见的item的索引和偏移量 int index = mList.getFirstVisiblePosition(); View v = mList.getChildAt(0); int top = (v == null) ? 0 : v.getTop(); // ... //根据上次保存的index和偏移量恢复上次的位置 mList.setSelectionFromTop(index, top);
/** * Sets the selected item and positions the selection y pixels from the top edge * of the ListView. (If in touch mode, the item will not be selected but it will * still be positioned appropriately.) * * @param position Index (starting at 0) of the data item to be selected. * @param y The distance from the top edge of the ListView (plus padding) that the * item will be positioned. */ publicvoidsetSelectionFromTop(int position, int y){ if (mAdapter == null) { return; } if (!isInTouchMode()) { position = lookForSelectablePosition(position, true); if (position >= 0) { setNextSelectedPositionInt(position); } } else { mResurrectToPosition = position; } if (position >= 0) { mLayoutMode = LAYOUT_SPECIFIC; mSpecificTop = mListPadding.top + y; if (mNeedSync) { mSyncPosition = position; mSyncRowId = mAdapter.getItemId(position); } requestLayout(); } }
/** * Sets the currently selected item. If in touch mode, the item will not be selected * but it will still be positioned appropriately. If the specified selection position * is less than 0, then the item at position 0 will be selected. * * @param position Index (starting at 0) of the data item to be selected. */ @Override publicvoidsetSelection(int position){ setSelectionFromTop(position, 0); }