2011-09-06 43 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); 
      } 
     } 
    } 
}; 
相关问题