Android ListView分页加载数据Demo
一个简单的Android分页加载数据的实例,实例中加载方式是滑动到底部自动加载下页数据,现在加载方式可以是点击拖拽一个自己定义的控件。
下面是一个主要的Activity代码:
01 public class MainActivity extends Activity {
02 private ListView listview;
03 private View footer;
04 private List<String> data;
05 private ArrayAdapter<String> adapter;
06
07 @Override
08 public void onCreate(Bundle savedInstanceState) {
09 super.onCreate(savedInstanceState);
10 setContentView(R.layout.main);
11 listview = (ListView) findViewById(R.id.listview);
12 // 给adapter添加数据
13 data = new DataService().getData();
14 adapter = new ArrayAdapter<String>(this, R.layout.item, R.id.tv_name, data);
15 // 必须在setAdapter之前把head和Footer设置好
16 footer = getLayoutInflater().inflate(R.layout.footer, null);
17 listview.addFooterView(footer);
18
19 // listview设置adpater
20 listview.setAdapter(adapter);
21 listview.removeFooterView(footer);
22 // 以上就可以显示ListView上的数据,可是不能分页显示,没有给LIstView添加滚动事件,
23 // 下面我们来给ListVIew添加滚动事件,从而达到自动刷新ListView分页加载数据的功能
24 listview.setOnScrollListener(new MyOnScrollListener());
25 }
26
27 public final class MyOnScrollListener implements OnScrollListener {
28 protected static final int GET_DATA_SUCCESS = 0;
29 private int pageCount = 20;
30 private int pageSize = 5;
31 // 是否加载完成
32 Boolean finish = true;
33 private Handler mHandler = new Handler() {
34 public void handleMessage(Message msg) {
35 msg.what = GET_DATA_SUCCESS;
36 List<String> result = (List<String>) msg.obj;
37 data.addAll(result);
38 finish = true;
39 if (listview.getFooterViewsCount() > 0) {
40 listview.removeFooterView(footer);
41 }
42 // 通知适配器更新数据
43 adapter.notifyDataSetChanged();
44 };
45 };
46
47 @Override
48 public void onScrollStateChanged(AbsListView view, int scrollState) {
49
50 }
51
52 @Override
53 public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
54 // 计算当前加载上来的全部item数目
55 int totalItem = firstVisibleItem + visibleItemCount;
56 // 计算当前页
57 int currenPage = totalItemCount / pageSize;
58 // 计算下一页的数值
59 int nextPage = currenPage + 1;
60 // 当 当前加载过的item总数目等于总显示过的Item数目的时候可以去加载
61 if (totalItem == totalItemCount) {
62 if (nextPage < pageCount && finish) {
63 finish = false;
64 listview.addFooterView(footer);
65 // 开始加载数据
66 new Thread() {
67 public void run() {
68 SystemClock.sleep(3000);
69 List<String> result = new DataService().getData();
70 Message msg = new Message();
71 msg.what = GET_DATA_SUCCESS;
72 msg.obj = result;
73 &n
补充:移动开发 , Android ,