首先查找XListView,设置是否激活下拉刷新,上拉加载,和他的下拉,上拉的监听事件
private XListView xlistView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xlistView = (XListView) findViewById(R.id.xlistView);
// 下拉刷新是否激活
xlistView.setPullRefreshEnable(true);
// 加载更多是否激活
xlistView.setPullLoadEnable(true);
// xlistView刷新和加载更多的监听
xlistView.setXListViewListener(this);
getData(1,refresh);
}
然后联网获取数据
public void getData(final int i,String path) {
HttpUtils httpUtils = new HttpUtils();
httpUtils.configCurrentHttpCacheExpiry(0);
httpUtils.send(HttpMethod.GET, path, new RequestCallBack<String>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
}
@Override
public void onSuccess(ResponseInfo<String> arg0) {
String result = arg0.result;
Gson gson = new Gson();
Data data = gson.fromJson(result, Data.class);
Message msg = Message.obtain();
msg.obj = data.getData();
msg.what = i;
handler.sendMessage(msg);
}
});
// 停止加载更多/刷新
public void loadOver() {
// 停止加载更多
xlistView.stopLoadMore();
// 停止刷新
xlistView.stopRefresh();
//设置刷新时的时间
xlistView.setRefreshTime(getTime());
}
这是监听上拉,下拉的监听
/**
* 刷新
*/
@Override
public void onRefresh() {
getData(2,refresh);
}
/**
* 加载更多
*/
@Override
public void onLoadMore() {
getData(3,more);
}
//设置时间
public String getTime(){
SimpleDateFormat format=new SimpleDateFormat("hh:mm:ss");
Date date=new Date();
String time = format.format(date);
return time;
}
使用Handler接收
LinkedList<DataBean> list = new LinkedList<DataBean>();
Handler handler = new Handler() {
private MyAdapter myAdapter;
@SuppressWarnings("unchecked")
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
// 加载初始化数据
case 1:
list = (LinkedList<DataBean>) msg.obj;
myAdapter = new MyAdapter(MainActivity.this, list);
xlistView.setAdapter(myAdapter);
loadOver();
break;
// 刷新
case 2:
list.clear();
for (DataBean dataBean : (LinkedList<DataBean>)msg.obj) {
//象开头添加
list.addFirst(dataBean);
}
// 刷新适配器
myAdapter.notifyDataSetChanged();
loadOver();
break;
// 加载更多
case 3:
for (DataBean dataBean : (LinkedList<DataBean>)msg.obj) {
//象结尾添加
list.addLast(dataBean);
}
// 刷新适配器
myAdapter.notifyDataSetChanged();
loadOver();
break;
}
};
};