[android]代码库
//MainActivity 代码
package com.example.loadrefresh;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.example.adapter.Adapter1;
import com.example.bean.Bean;
import com.example.bean.Mylist;
import com.example.view.XListView;
import com.example.view.XListView.IXListViewListener;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import android.R.integer;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
public class MainActivity extends Activity implements IXListViewListener {
private XListView lv;
private int num=1;
private URL url;
List<Mylist> list=new ArrayList<Mylist>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (XListView) findViewById(R.id.list);
//初始化时加载数据
getdata("initialize", num);
//开启加载更多
lv.setPullLoadEnable(true);
//上拉加载,下拉刷新监听
lv.setXListViewListener(this);
}
//下拉刷新
@Override
public void onRefresh() {
// TODO Auto-generated method stub
num+=1;
getdata("Refresh", num);
}
//上拉加载
@Override
public void onLoadMore() {
// TODO Auto-generated method stub
num+=1;
getdata("Load", num);
}
private Adapter1 adapter1;
//查询数据
public void getdata(final String string,int num){
HttpUtils httpUtils=new HttpUtils();
String string2="http://v.juhe.cn/weixin/query?key=484057f2721591bc4730f6b370c7ff31&pno="+num;
httpUtils.send(HttpMethod.GET, string2, new RequestCallBack<String>(){
@Override
public void onFailure(HttpException arg0, String arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSuccess(ResponseInfo<String> arg0) {
// TODO Auto-generated method stub
String string3 = arg0.result;
Bean bean = new Gson().fromJson(string3, Bean.class);
adapter1 = new Adapter1(MainActivity.this, list);
//判断是否为初始化数据
if(string.equals("initialize")){
list.addAll(bean.result.list);
lv.setAdapter(adapter1);
}else
//判断是否是上拉加载
if(string.equals("Load")){
//直接刷新适配器
list.addAll(bean.result.list);
adapter1.notifyDataSetChanged();
lv.stopLoadMore();
}else
//判断是否是下拉刷新
if(string.equals("Refresh")){
//创建另一个集合
List<Mylist> list2=new ArrayList<Mylist>();
list2.clear();
//将数据添加进list2
list2.addAll(bean.result.list);
//将list2放进list集合(而且是放进list集合的最前方)
list.addAll(0, list2);
//重新创建适配器添加数据
adapter1 = new Adapter1(MainActivity.this, list);
lv.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
//关闭刷新
lv.stopRefresh();
//获取上一次刷新时间
SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
Date date=new Date();
dateFormat.format(date);
lv.setRefreshTime(dateFormat.format(date));
}
}
});
}
}