import android.os.AsyncTask;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import com.bawei.jane.mxlistview.view.XListView;import com.google.gson.Gson;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import adapter.MyAdapter;import bean.Result;public class MainActivity extends AppCompatActivity { private XListView xlv; private int pageIndex=1;//第一頁的數據 private String urlpart="http://www.yulin520.com/a2a/impressApi/news/mergeList?pageSize=10&page="; private String url =urlpart + pageIndex; private MyAdapter adapter; private List<Result.DataBean>data = new ArrayList<>(); private int operType = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控件 xlv = findViewById(R.id.xlv); //對xlistview進行設置 xlv.setPullLoadEnable(true);//上拉加載更多 xlv.setPullRefreshEnable(true);//下拉刷新 //設置接口 xlv.setXListViewListener(new XListView.IXListViewListener() { @Override public void onRefresh() {//刷新 //刷新時,從新請求第一頁的數據 pageIndex = 1; url = urlpart+pageIndex; //從新賦值 operType = 1; MyTask myTask = new MyTask(); myTask.execute(url); } @Override public void onLoadMore() {//加載更多 //頁數增長 pageIndex++; url = urlpart+pageIndex; //從新賦值 operType =2; MyTask task = new MyTask(); task.execute(url); } }); //進行網絡請求 MyTask myTask = new MyTask(); myTask.execute(url); } class MyTask extends AsyncTask<String,Void,String>{ @Override protected String doInBackground(String... strings) { StringBuilder builder = new StringBuilder(); try { URL url = new URL(strings[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setReadTimeout(5000); if (connection.getResponseCode()==200){ InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String str; while ((str=reader.readLine())!=null){ builder.append(str); } reader.close(); } } catch (Exception e) { e.printStackTrace(); } return builder.toString(); } @Override protected void onPostExecute(String s) { Gson gson =new Gson(); Result result = gson.fromJson(s, Result.class); if (operType==1) {//表明刷新操做 data.clear();//清空原有的集合數據 } //增長新的數據集合到原來的集合對象中 data.addAll(result.getData()); setAdapter(); //關閉頭尾佈局 if (operType==1){ xlv.stopRefresh();//關閉頭佈局 Date date = new Date(System.currentTimeMillis());//獲取當前時間 SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化時間 String refreShTime = sf.format(date); xlv.setRefreshTime(refreShTime);//設置刷新時間 }else{ xlv.stopLoadMore();//關閉尾佈局 } } } public void setAdapter(){ if (adapter ==null){ adapter = new MyAdapter(data,MainActivity.this); xlv.setAdapter(adapter); }else{ adapter.notifyDataSetChanged(); } } }