android中ListView的定位:使用setSelectionFromTop

TZL818 8年前發布 | 10K 次閱讀 Android開發 移動開發

 如果一個ListView太長,有時我們希望ListView在從其他界面返回的時候能夠恢復上次查看的位置,這就涉及到ListView的定位問題:

解決的辦法如下:

// 保存當前第一個可見的item的索引和偏移量
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// ...
//根據上次保存的index和偏移量恢復上次的位置
mList.setSelectionFromTop(index, top);

這里使用了setSelectionFromTop來定位ListView。其實還可以使用setSelection也可以定位,只是setSelectionFromTop要比setSelection更精準。因為通過getFirstVisiblePosition得到的第一個item可能已經有一部分是不可見的了,如果用setSelection無法反映出這不可見的部分。


為了說明setSelectionFromTop的參數值的意義,以及與setSelection的區別,下面從源碼上來分析:

看一下setSelectionFromTop()的具體實現,代碼如下:

/**
  * 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.
  */
 public void setSelectionFromTop(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();
     }
 }

從上面的代碼可以得知,setSelectionFromTop()的作用是設置ListView選中的位置,同時在Y軸設置一個偏移量

而setSelection()方法,傳入一個index整型數值,就可以讓ListView定位到指定Item的位置。

這兩個方法有什么區別呢?看一下setSelection()的具體實現,代碼如下:

/**
  * 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
 public void setSelection(int position) {
     setSelectionFromTop(position, 0);
 }

原來,setSelection()內部就是調用了setSelectionFromTop(),只不過是Y軸的偏移量是0而已。現在應該對setSelection()和setSelectionFromTop()有了更深刻的認識了。

 本文由用戶 TZL818 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!