public class MainActivity extends AppCompatActivity {
private PullToRefreshListView pullToRefreshListView;
private HttpUtils httpUtils = HttpUtils.getInstance();
private String path = "http://www.yulin520.com/a2a/impressApi/news/mergeList?pageSize=15&page=";
private int page =1;
private List<UserBean.DataBean> list = new ArrayList<>();
private MyBase adapter;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.定义方法
initView();
getData();
}
//设置头部底部的视图
private void initView() {
//获取资源ID
pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_listView);
//2.设置模式 BOTH 可以上拉 下拉 pull_from_end代表上拉,pull_from_start代表下拉
pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
//3.都是布尔类型 第一个如果为true 时 当前设置的就是头部 如果第二个为true设置的就是底部
final ILoadingLayout startLoadding = pullToRefreshListView.getLoadingLayoutProxy(true,false);
startLoadding.setPullLabel("下拉刷新");
startLoadding.setRefreshingLabel("正在刷新");
startLoadding.setReleaseLabel("放开刷新");
ILoadingLayout endLoadding = pullToRefreshListView.getLoadingLayoutProxy(false,true);
endLoadding.setPullLabel("上拉加载");
endLoadding.setRefreshingLabel("正在加载");
endLoadding.setReleaseLabel("放开加载");
//4.接口回调上拉下拉
pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
//11.在下拉完成后被回调
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
page =1;
getData();
//12.
handler.postDelayed(new Runnable() {
@Override
public void run() {
//必须在异步中完成 在列表没有数据的时候,不再请求接口,调用当前方法
pullToRefreshListView.onRefreshComplete();
}
},2000);
//可以设置刷新的时间....
startLoadding.setLastUpdatedLabel("上次更新时间:"+new SimpleDateFormat("HH:mm").format(new Date(System.currentTimeMillis())));//last最近的,最后一次update修改/更新
}
//11.在上拉完成后被回调
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
page+=1;
getData();
//12.
handler.postDelayed(new Runnable() {
@Override
public void run() {
pullToRefreshListView.onRefreshComplete();
}
},2000);
}
});
//9.创建适配器
adapter = new MyBase(list,MainActivity.this);
pullToRefreshListView.setAdapter(adapter);
}
//5.得到数据
public void getData(){
final String url = path+page;
httpUtils.getdata(url);
//6.接口回调得到数据
httpUtils.setHttpListener(new HttpUtils.HttpListener() {
@Override
public void getjsondata(String json) {
//开始解析
Gson gson = new Gson();
UserBean userBean = gson.fromJson(json, UserBean.class);
//7.解析出来的数据
List<UserBean.DataBean> data = userBean.getData();
//8.在list集合中添加数据
Log.i("TAG",data.size()+"");
//如果是第一页的数据 清空集合
if(page == 1){
list.clear();
}
//将请求到的数据刷新
list.addAll(data);
//10.刷新适配器
adapter.notifyDataSetChanged();
}
});
}