在listview中实现分页

时间:2011-12-06 07:39:10

标签: android android-layout android-listview paging

实际上我有一个包含30个项目的列表视图。我想实现分页,即将两个按钮作为下一个&以前,当我点击下一步它显示约5项等等。

请提供示例代码

3 个答案:

答案 0 :(得分:1)

一种解决方案是实现OnScrollListener并在onScroll方法中以方便的状态对ListAdapter进行更改(如添加项目等)。

当用户滚动到列表末尾时添加项目。Click here

答案 1 :(得分:0)

您还可以添加页脚元素(加载更多...)。

要做到这一点,你必须:

View footer = getLayoutInflater().inflate(R.layout.item_load_more, null);
myList.addFooterView(footer);

您还可以在listview结束时加载更多项目,例如:http://benjii.me/2010/08/endless-scrolling-listview-in-android/

希望这会有所帮助......

答案 2 :(得分:0)

我做了这样的事情。你也可以试试。它工作得很好

public boolean onTouchEvent(MotionEvent ev) {
    final int action = ev.getAction();
    if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
        //here i handled continous move
        scrolltwice = true;
        return true;
    }

    final float x = ev.getX();
    final float y = ev.getY();
    switch(action & MotionEvent.ACTION_MASK){

    case MotionEvent.ACTION_MOVE:

        final int xDiff = (int) Math.abs(x - mLastMotionX);
        yDiff = (int) (y - mLastMotionY);
        final int ydif = (int) Math.abs(y - mLastMotionY);

        final int touchSlop = mTouchSlop;
        boolean xMoved = xDiff > touchSlop;
        boolean yMoved = ydif > touchSlop;
        if (xMoved || yMoved) {
            if (yMoved) {                   
                mTouchState = TOUCH_STATE_SCROLLING;
            }
        }
        break;

    case MotionEvent.ACTION_DOWN:

        if (!mScroller.isFinished()) {
            mScroller.abortAnimation();
        }
        // Remember location of down touch
        mLastMotionX = x;
        mLastMotionY = y;           
        break;
    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:

        final int myDiff = (int) (y - mLastMotionY);

        if(mTouchState == TOUCH_STATE_SCROLLING){
            scrolltwice = false;
            if(!scrolltwice){
            Log.d("DB", " ACTION_UP fetch new records ");
                FetchRecords rec = new FetchRecords();
                rec.execute();  
                if(yDiff < 0){ // fetching next slot of records
                    nextRecordId = nextRecordId + previousTotal;
                    if(nextRecordId > totalRowCount){
                        nextRecordId = nextRecordId - previousTotal;
                    }
                }else if(yDiff > 0){ // fetching previous slot of records
                    nextRecordId = nextRecordId - previousTotal;
                    if(nextRecordId < 1){
                        nextRecordId = 0;
                    }
                }
            }
        }
        scrolltwice = false;
        mTouchState = TOUCH_STATE_REST;
        break;
    }
    return false;

}

      //implement ontouch listener if the view is list pass it onTouchEvent
public boolean onTouch(View v, MotionEvent event) {
    if(v.equals(objListView))
        onTouchEvent(event);
    return false;
}