在Android中有很多时候会选择用ListView加载数据,有的是分批加载,比如每次加载20条,100条就要加载5次,如果一次性加载100条,ListView加载就会变慢,如果是有图片的话,一是浪费流量,二是item中带图片会出现错位的问题,ListView加载数据目前好多App的做法:
1. 分批加载,滑动到底部自动更新
2. 滑动到底部,手动的点击加载更多
3. 下拉刷新 + 底部加载更多
今天实现ListView滑动到底部自动更新的效果。
原理:监听ListView的滑动事件,判断ListView是否滑动到底部,然后去加载数据。
1. public class MainActivity extends Activity {
2. private ListView listview;
3. private List<String> datas;
4. private LayoutInflater inflater;
5. private MyAdapter adapter;
6. private List<String> contents;
7. private int count = 0;
8. private View footView;
9. private Handler handler = new Handler();
10. int lastItem;
11. private RelativeLayout loading;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16. initData();
17. this);
18. listview = (ListView) findViewById(R.id.listview);
19. new MyAdapter();
20. null);
21. loading = (RelativeLayout) footView.findViewById(R.id.loading);
22. //listview的addFooterView()添加view到listview底部一定要加在listview.setAdapter(adapter);这代码前面
23. listview.addFooterView(footView);
24. listview.setAdapter(adapter);
25. //添加listview滚动监听
26. new OnScrollListener() {
27. //AbsListView view 这个view对象就是listview
28. @Override
29. public void onScrollStateChanged(AbsListView view, int scrollState) {
30. if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
31. if (view.getLastVisiblePosition() == view.getCount() - 1) {
32. loadData();
33. }
34. }
35. }
36. @Override
37. public void onScroll(AbsListView view, int firstVisibleItem,
38. int visibleItemCount, int totalItemCount) {
39. 1 ;
40. }
41. });
42. }
43. protected void loadData() {
44. loading.setVisibility(View.VISIBLE);
45. new Runnable() {
46. @Override
47. public void run() {
48. load();
49. loading.setVisibility(View.GONE);
50. adapter.notifyDataSetChanged();
51. }
52. 5000);
53. }
54. protected void load() {
55. int count = adapter.getCount() + 1;
56. for(int i = count; i < count + 20; i++) { //每次加载20条数据
57. "加载数据:::" + i);
58. }
59. }
60. private void initData() {
61. new ArrayList<String>();
62. for(int i = 1; i < 20; i++){
63. "加载数据:::" + i);
64. }
65. }
66.
67. class MyAdapter extends BaseAdapter{
68. @Override
69. public int getCount() {
70. return contents.size();
71. }
72. @Override
73. public Object getItem(int position) {
74. return contents.get(position);
75. }
76.
77. @Override
78. public long getItemId(int position) {
79. return position;
80. }
81.
82. @Override
83. public View getView(int position, View convertView, ViewGroup parent) {
84. ViewHolder holder;
85. if(convertView == null){
86. false);
87. new ViewHolder();
88. holder.tvContent = (TextView) convertView.findViewById(R.id.tvContent);
89. convertView.setTag(holder);
90. else{
91. holder = (ViewHolder) convertView.getTag();
92. }
93. holder.tvContent.setText(contents.get(position));
94. return convertView;
95. }
96. class ViewHolder{
97. TextView tvContent;
98. }
99. }
100. }