listview通过onscrollListener实现分页加载

package com.bwie.listviewloadmore;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity implements OnScrollListener {

    private ListView lv;
    private ArrayList<String> list;
    private boolean isLoad = false;
    int count = 1;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 找到该布局文件下的控件
        lv = (ListView) findViewById(R.id.lv);
        // 创建集合对象
        list = new ArrayList<String>();
        // 为lv设置数据
        setData("");

        // 为lv设置适配器
        adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_expandable_list_item_1, list);
        lv.setAdapter(adapter);

        // 为lv设置滚动监听事件
        lv.setOnScrollListener(this);

    }

    private void setData(String param) {

        for (int i = 0; i < 30; i++) {
            list.add(param + "data" + i);
        }

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub
        // listview滑动到底部,并且listview处于静止的状态
        if (scrollState == SCROLL_STATE_IDLE && isLoad) {
            count++;
            // 重新请求网络数据
            setData("web" + count);

            // 刷新适配器
            adapter.notifyDataSetChanged();

        }

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        // TODO Auto-generated method stub
        // 判断是否需要加载另一页数据
        isLoad = (firstVisibleItem + visibleItemCount) == totalItemCount;

    }

}

 

posted on 2016-04-17 19:43  IT心得  阅读(367)  评论(0编辑  收藏  举报