【Android 疑難雜症】setSelection和setSelectionFromTop探究,androidselection
通常,app中的資料都是以ListView的形式展示的。預設地,把“新”資料添加到資料列表的尾部。
但是,如果是IM類型的app,比如查看曆史訊息這個模組。新資料並不是插到資料列表的尾部,而是插到資料列表的頭部。
要實現比較好的使用者體驗,需要保持當前的ListView的位置。換句話說,如果我們能夠隨心所欲地指定ListView滾動的位置,那麼這個問題就迎刃而解。
在ListView中,有一個setSelectionFromTop()方法,下面是一個使用範例。代碼如下:
@Override public void loaded(Long loadTime, int thisPageNumber, boolean isFromZero, boolean isHasMoreToLoad, List data) { refreshComplete(); checkIfHasMoreToLoad(isHasMoreToLoad); if (thisPageNumber != 1) {// 不是第一頁 mListView.setSelectionFromTop(5+2, mIMPullToRefreshListView.getHeaderHeight()); mIMPullToRefreshListView.getHeaderView().setVisibility(View.GONE); } }
看一下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軸設定一個位移量(padding值)。
ListView還有一個方法叫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()有了更深刻的認識了。
參考資料
http://developer.android.com/reference/android/widget/ListView.html#setSelection%28int%29
http://www.cnblogs.com/over140/archive/2013/05/20/2948239.html
http://blog.csdn.net/jdsjlzx/article/details/17794209
http://blog.csdn.net/a859522265/article/details/8154103
android editText setselection屬性的時為何老是會定位到螢幕的下方,可以不可以定位到螢幕的上方或者中間
我記憶中的setSelection 好像是定位編輯的游標位置,EditText中好像可以設定游標在內容的最尾端。
Android 的ListView控制項中,怎使選中項停留的列表的中間位置?
對ListView設定onScrollListener來監聽onScroll事件,擷取當前的firstVisibleItem,visibleItemCount。對ListView設定OnItemClickListener來監聽itemclick事件擷取選中的item的索引,調用listView的setSelection(int index)方法重新置放一次listView的選中位置,其中index需要根據itemClick事件擷取的索引和scroll事件擷取的值來計算。這個沒驗證過不知道準不準,應該還有更好的方法,求大牛。