ListView的setSelectionFromTop()方法與setSelection()方法的聯系


 

 

通常,app中的數據都是以ListView的形式展示的。默認地,把“新”數據添加到數據列表的尾部。

 

但是,如果是IM類型的app,比如查看歷史消息這個模塊。新數據並不是插到數據列表的尾部,而是插到數據列表的頭部。

 

要實現比較好的用戶體驗,需要保持當前的ListView的位置。換句話說,如果我們能夠隨心所欲地指定ListView滾動的位置,那么這個問題就迎刃而解。

 

在ListView中,有一個setSelectionFromTop()方法,下面是一個使用范例。代碼如下:

 

 1     @Override  
 2     public void loaded(Long loadTime, int thisPageNumber, boolean isFromZero, boolean isHasMoreToLoad, List data) {  
 3         refreshComplete();  
 4         checkIfHasMoreToLoad(isHasMoreToLoad);  
 5       
 6         if (thisPageNumber != 1) {// 不是第一頁  
 7             mListView.setSelectionFromTop(5+2, mIMPullToRefreshListView.getHeaderHeight());  
 8             mIMPullToRefreshListView.getHeaderView().setVisibility(View.GONE);  
 9         }  
10     }  

 

 

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

 

 1 /** 
 2  * Sets the selected item and positions the selection y pixels from the top edge 
 3  * of the ListView. (If in touch mode, the item will not be selected but it will 
 4  * still be positioned appropriately.) 
 5  * 
 6  * @param position Index (starting at 0) of the data item to be selected. 
 7  * @param y The distance from the top edge of the ListView (plus padding) that the 
 8  *        item will be positioned. 
 9  */  
10 public void setSelectionFromTop(int position, int y) {  
11     if (mAdapter == null) {  
12         return;  
13     }  
14   
15     if (!isInTouchMode()) {  
16         position = lookForSelectablePosition(position, true);  
17         if (position >= 0) {  
18             setNextSelectedPositionInt(position);  
19         }  
20     } else {  
21         mResurrectToPosition = position;  
22     }  
23   
24     if (position >= 0) {  
25         mLayoutMode = LAYOUT_SPECIFIC;  
26         mSpecificTop = mListPadding.top + y;  
27   
28         if (mNeedSync) {  
29             mSyncPosition = position;  
30             mSyncRowId = mAdapter.getItemId(position);  
31         }  
32   
33         requestLayout();  
34     }  
35 } 

 

 

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

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

 

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

 

 
 1     /** 
 2      * Sets the currently selected item. If in touch mode, the item will not be selected 
 3      * but it will still be positioned appropriately. If the specified selection position 
 4      * is less than 0, then the item at position 0 will be selected. 
 5      * 
 6      * @param position Index (starting at 0) of the data item to be selected. 
 7      */  
 8     @Override  
 9     public void setSelection(int position) {  
10         setSelectionFromTop(position, 0);  
11     }  

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM