2011-09-06 82 views

回答

0

創建一個「反彈時」的觀點:

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
> 
    <View 
    android:layout_width="fill_parent" 
    android:layout_height="320px" 
    android:background="@android:color/transparent" 
    /> 
</LinearLayout> 

您需要在主要活動的一些全局變量:

private int currentScrollState = OnScrollListener.SCROLL_STATE_IDLE; 
// itemAtTop and itemOffset are needed for when the listview doesn't have enough items to fill the screen 
private int itemAtTop = 0, itemOffset = 0; // reset both to 0 each time you populate the listview 
private Handler mHandler = new Handler(); 

在主要活動的onCreate,設置ListView的適配器之前,添加頁眉和頁腳:

View v  = LayoutInflater.from(this).inflate(R.layout.listview_overscrollview, null); 
listview.addHeaderView(v, null, false); 
listview.addFooterView(v, null, false); 
listview.setOnScrollListener(this); 

您的主要活動必須覆蓋2個方法,因爲se tOnScrollListener:

@Override 
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) 
{ 
    checkTopAndBottom(); 
} 


@Override 
public void onScrollStateChanged(AbsListView view, int scrollState) 
{ 
    currentScrollState = scrollState; 
    checkTopAndBottom(); 
} 

的checkTopAndBottom()函數,它應該也可以在列表視圖後稱爲是(重新)填充:

public void checkTopAndBottom() 
{ 
    if (listview.getCount() <= 2) return; // do nothing, only header and footer in listview 
    if (scrollState != OnScrollListener.SCROLL_STATE_IDLE) return; // do nothing, listview still scrolling 
    if (listview.getFirstVisiblePosition() < 1) { 
     listview.setSelectionFromTop(1, -1); 
    } 
    if (listview.getLastVisiblePosition() == listview.getCount()-1) { 
     listview.setSelectionFromTop(listview.getCount()-1, listview.getHeight()); 
    } 
    mHandler.post(checkListviewBottom); 
} 

最後可運行(用於listview.getFirstVisiblePosition()等是最新的):

private final Runnable checkListviewBottom = new Runnable() 
{ 
    @Override 
    public void run() { 
     if (listview.getLastVisiblePosition() == listview.getCount()-1) { 
      if (itemAtTop == 0) { 
       if (listview.getFirstVisiblePosition() <= 1) { 
        itemAtTop = 1; 
        itemOffset = -1; 
       } else { 
        itemAtTop = listview.getCount()-1; 
        itemOffset = listview.getHeight()+1; 
       } 
      } 
      if (itemAtTop == listview.getCount()-1 || (itemAtTop == 1 && listview.getFirstVisiblePosition() > 0)) { 
       listview.setSelectionFromTop(itemAtTop, itemOffset); 
      } 
     } 
    } 
}; 
相關問題