你的位置:首页 > 操作系统

[操作系统]下拉刷新原理。


 1 package com.lixu.listviewrefresh; 2  3 import java.util.ArrayList; 4  5 import android.app.Activity; 6 import android.os.Bundle; 7 import android.widget.AbsListView; 8 import android.widget.AbsListView.OnScrollListener; 9 import android.widget.ArrayAdapter;10 import android.widget.ListView;11 12 public class MainActivity extends Activity {13   private ArrayList<String> data;14   private ArrayAdapter<String> mMyAdapter;15 16   @Override17   protected void onCreate(Bundle savedInstanceState) {18     super.onCreate(savedInstanceState);19     setContentView(R.layout.activity_main);20 21     data = new ArrayList<String>();22 23     for (int i = 0; i < 30; i++) {24       data.add("测试数据" + i);25     }26 27     ListView lv = (ListView) findViewById(R.id.listview);28 29     mMyAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);30 31     lv.setAdapter(mMyAdapter);32 33     lv.setOnScrollListener(new OnScrollListener() {34       private int firstVisibleItem;35       private int visibleItemCount;36       private int totalItemCount;37 38       @Override39       public void onScrollStateChanged(AbsListView view, int scrollState) {40         // 当滑动停止的时候判断41         if (OnScrollListener.SCROLL_STATE_IDLE == scrollState) {42 43           if (firstVisibleItem == 0) {44 45             data.add(0, "增加头部数据" + (totalItemCount + 1));46 47             mMyAdapter.notifyDataSetChanged();48 49           }50         }51 52         if (OnScrollListener.SCROLL_STATE_IDLE == scrollState) {53 54           if ((firstVisibleItem + visibleItemCount) == totalItemCount) {55 56             data.add("增加尾部数据" + (totalItemCount + 1));57 58             mMyAdapter.notifyDataSetChanged();59 60           }61         }62 63       }64 65       @Override66       public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {67 68         this.firstVisibleItem = firstVisibleItem;69         this.visibleItemCount = visibleItemCount;70         this.totalItemCount = totalItemCount;71 72       }73     });74 75   }76 77 }

效果图: