PullToRefreshListView上拉下拉重新整理
阿新 • • 發佈:2019-02-14
//main方法
import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ListView; import com.example.day16.Bean.ResultBean; import com.example.day16.Utils.MyTask; import com.example.day16.adapter.MyAdapter; importcom.google.gson.Gson; import com.handmark.pulltorefresh.library.ILoadingLayout; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { privatePullToRefreshListView pullToRefreshListView; private List<ResultBean.NewslistBean> list=new ArrayList<>(); private Handler myHandler = new Handler(); private MyAdapter adapter; private int index=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_lv); //設定重新整理載入 SetPtrLv(); //初始化資料 initData(); } //初始化資料 public void initData(){ MyTask myTask=new MyTask(new MyTask.Icallbacks() { @Override public void updateUiByjson(String jsonstr) { Gson gson=new Gson(); ResultBean resultBean = gson.fromJson(jsonstr, ResultBean.class); List<ResultBean.NewslistBean> newslist = resultBean.getNewslist(); list.addAll(newslist); //設定資料 setAdapter(); } }); myTask.execute("https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=1"); } //上拉載入 private void addtoBottom(){ MyTask myTask=new MyTask(new MyTask.Icallbacks() { @Override public void updateUiByjson(String jsonstr) { Gson gson=new Gson(); ResultBean resultBean = gson.fromJson(jsonstr, ResultBean.class); List<ResultBean.NewslistBean> newslist = resultBean.getNewslist(); list.addAll(newslist); } }); index++; myTask.execute("https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page="+index); } //下拉重新整理 private void addtoTop(){ MyTask myTask=new MyTask(new MyTask.Icallbacks() { @Override public void updateUiByjson(String jsonstr) { Gson gson=new Gson(); ResultBean resultBean = gson.fromJson(jsonstr, ResultBean.class); List<ResultBean.NewslistBean> newslist = resultBean.getNewslist(); // list.addAll(0,newslist); list.clear(); list.addAll(newslist); } }); myTask.execute("https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=1"); } private void setAdapter(){ if(adapter==null){ adapter=new MyAdapter(this,list); pullToRefreshListView.setAdapter(adapter); }else{ adapter.notifyDataSetChanged(); } } private void SetPtrLv() { //設定重新整理模式 pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH); /**這裡通過getLoadingLayoutProxy 方法來指定上拉和下拉時顯示的狀態的區別, * 第一個true 代表下來狀態 ,第二個true 代表上拉的狀態 如果想區分上拉和下拉狀態的不同,可以分別設定*/ ILoadingLayout startLabels = pullToRefreshListView.getLoadingLayoutProxy(true, false); startLabels.setPullLabel("下拉重新整理"); startLabels.setRefreshingLabel("正在拉"); startLabels.setReleaseLabel("放開重新整理"); ILoadingLayout endLabels = pullToRefreshListView.getLoadingLayoutProxy(false, true); endLabels.setPullLabel("上拉重新整理"); endLabels.setRefreshingLabel("正在載入..."); endLabels.setReleaseLabel("放開重新整理..."); pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉重新整理的回撥 //下拉重新整理的資料,顯示在listview列表的最上面 addtoTop(); myHandler.postDelayed(new Runnable() { @Override public void run() { //重新整理完成,必須在非同步下完成 pullToRefreshListView.onRefreshComplete(); //重新整理介面卡 setAdapter(); } }, 1000); } @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉載入的回撥 //載入更多的資料,新增到集合列表的最後面 addtoBottom(); myHandler.postDelayed(new Runnable() { @Override public void run() { //重新整理完成,必須在非同步下完成 pullToRefreshListView.onRefreshComplete(); //重新整理介面卡 setAdapter(); } }, 1000); } }); } } //介面卡
public class MyAdapter extends BaseAdapter { private Context context; private List<ResultBean.NewslistBean> list; public MyAdapter(Context context, List<ResultBean.NewslistBean> list) { this.context = context; this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView==null){ convertView=View.inflate(context, R.layout.item,null); holder=new ViewHolder(); holder.imageView= (ImageView) convertView.findViewById(R.id.img); holder.textView= (TextView) convertView.findViewById(R.id.tv); convertView.setTag(holder); }else{ holder= (ViewHolder) convertView.getTag(); } holder.textView.setText(list.get(position).getTitle()); ImageLoader.getInstance().displayImage(list.get(position).getPicUrl(),holder.imageView, ImageloaderUtil.getImageOptions()); return convertView; } class ViewHolder{ ImageView imageView; TextView textView; } }
//bean包解析的資料
public class ResultBean { /** * code : 200 * msg : success * newslist : [{"ctime":"2017-10-19","title":"讓步,是涵養,也是善良!","description":"中國新聞網","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-35939643.jpg/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392830&signature=gYnmAYHNvNo89UvsFp3J-HmGbryQlgpZiQTPTnPAFXBB6ONG9fHlmHeRv6-MwSCIt9tjpk1OpyoeKMWEFTWc0EzmTNBXUx5KN5Kw3AFnunQ="},{"ctime":"2017-10-19","title":"一群北大清華醫學學霸開了家\u201c柳葉刀\u201d燒烤店,結果《柳葉刀》主編真的來吃了\u2026\u2026","description":"中國日報","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-53210239.static/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392829&signature=N2PGRhHbYwzRHFdS7JhFgFCFuPKZCky*g*csWBITxpMTHksiowkOUJSDRcmAEWWOiOKYxhFyq0yobrkTzCJsEBjlSfxGqlP7PgwkpnNqEk0="},{"ctime":"2017-10-19","title":"同樣是貓頭鷹,差別咋就這麼大捏?","description":"動物世界","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-55363306.jpg/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392829&signature=aF6YAkKWtxrCqnlh3tlKvhZ8ZnpPmj1I9iblTtvmxZ2zMAt3w6anSBpqnRk86kRneghrrpqDHUCLy*rrlPqtcpkm*een8ypt-cyi3qaAGVQ="},{"ctime":"2017-10-19","title":"動物世界犬種-牛頭梗","description":"動物世界","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-55363291.jpg/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392829&signature=vIBu1M3tp0o4CSUYct3-n*dyf8JKYFZ8GEPXx5IPMocbASAS-qLYzNN1X08DeyB5tp4q8CBGUG1L51GKd1J685fsBbGLf1aozoHYSBs0Law="},{"ctime":"2017-10-19","title":"獨家 | 8斤以上\u201c巨大兒\u201d屬於病理性體重!專家這樣解釋原因","description":"嘉定報社","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-55363141.jpg/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392828&signature=Bkr0588AC*w9YAVLgp4fqVo*kJ*S3l7aYPISCsTbyc*TRBCFEI4IG2ZwRgd8CLcH2pkCVdi5W7H9gpu3FnY3G8crvwzJcumEurGY0qXwkso="},{"ctime":"2017-10-19","title":"重磅 | 總分150!你給你家小區打幾分?","description":"嘉定報社","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-36596651.static/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392828&signature=laK6fjPmTixJdH*L4YKzT4QoUmFO7s6YHmKPXVLANtTcZywTQldtyHWxzJnjsZ41OWICxCSpRJqglns9a-VW7AXPbYk42b1KKv4qQxacR-c="},{"ctime":"2017-10-19","title":"【隴南故事會】不知道你對三妻四妾這種傳統怎麼看?","description":"隴南都市網","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-19458195.jpg/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392827&signature=jskRpa-TqyThbvz-Sge59PpLZxbnoRfxiquep243Benoex41BSc8we0P4BD5IgulKz2YIG8fi0weLGsKryN*Fx8YqC9KO3LljkAYR88zqnc="},{"ctime":"2017-10-19","title":"我的世界,你曾經來過","description":"散文吧美麗如雪","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-37618338.static/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392827&signature=gaQsYJN9x0WhLVM166mMfkgoVmVC6hKfmvA3A1mE7R6STDKPLBSRvezdzOgt1Hhb*xIuiBp5h1gLO8rpWo6q-MvByH5vzNGw8xJoZh6TyuA="},{"ctime":"2017-10-19","title":"隴南沒考駕照的恭喜了!央視傳來大訊息... ?","description":"隴南都市網","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-19458195.jpg/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392827&signature=0mmcBR-tBhJww81w*6KKn0fMJIFAxUgeAmTlHgB4OfsvT7U7KeZfVA-oX9YlpoDgX4Hfn1RDvJXaABAzzFf3kLNjsG5qcqVAGxWZWrZpYCs="},{"ctime":"2017-10-19","title":"封面 |我喜歡好看的皮囊,也喜歡她善良的心","description":"隴南都市網","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-52003529.jpg/640","url":"https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392827&signature=32tc2KpGVVYucsDmesoMtU-nfD7cH*KSUiunmofrGeGMKAw5ttNM7N6AobSgqqpco68jeBayCGMFNwY1w2f7nBhVaRD09aAotfhgai-3qZw="}] */ private int code; private String msg; private List<NewslistBean> newslist; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<NewslistBean> getNewslist() { return newslist; } public void setNewslist(List<NewslistBean> newslist) { this.newslist = newslist; } public static class NewslistBean { /** * ctime : 2017-10-19 * title : 讓步,是涵養,也是善良! * description : 中國新聞網 * picUrl : https://zxpic.gtimg.com/infonew/0/wechat_pics_-35939643.jpg/640 * url : https://mp.weixin.qq.com/s?src=16&ver=436×tamp=1508392830&signature=gYnmAYHNvNo89UvsFp3J-HmGbryQlgpZiQTPTnPAFXBB6ONG9fHlmHeRv6-MwSCIt9tjpk1OpyoeKMWEFTWc0EzmTNBXUx5KN5Kw3AFnunQ= */ private String ctime; private String title; private String description; private String picUrl; private String url; public String getCtime() { return ctime; } public void setCtime(String ctime) { this.ctime = ctime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } }
//工具包
public class ImageloaderUtil { /** * ImageLoader的配置 * @param context */ public static void initConfig(Context context) { //配置 // File cacheFile=context.getExternalCacheDir(); File cacheFile= new File(Environment.getExternalStorageDirectory()+"/"+"imgages"); ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(context) .memoryCacheExtraOptions(480, 800)//快取圖片最大的長和寬 .threadPoolSize(2)//執行緒池的數量 .threadPriority(4) .memoryCacheSize(2*1024*1024)//設定記憶體快取區大小 .diskCacheSize(20*1024*1024)//設定sd卡快取區大小 .diskCache(new UnlimitedDiskCache(cacheFile))//自定義快取目錄 .writeDebugLogs()//列印日誌內容 .diskCacheFileNameGenerator(new Md5FileNameGenerator())//給快取的檔名進行md5加密處理 .build(); ImageLoader.getInstance().init(config); } /** * 獲取圖片設定類 * @return */ public static DisplayImageOptions getImageOptions(){ DisplayImageOptions optionsoptions=new DisplayImageOptions.Builder() .cacheInMemory(true)//使用記憶體快取 .cacheOnDisk(true)//使用磁碟快取 .bitmapConfig(Bitmap.Config.RGB_565)//設定圖片格式 .build(); return optionsoptions; } }
//工具包
public class MyTask extends AsyncTask<String,Void,String> { //申請一個介面類物件 private Icallbacks icallbacks; //將無參構造設定成私有的,使之在外部不能夠呼叫 private MyTask(){} //定義有參構造方法 public MyTask(Icallbacks icallbacks) { this.icallbacks = icallbacks; } @Override protected String doInBackground(String... params) { String str=""; try { //使用HttpUrlConnection URL url=new URL(params[0]); HttpURLConnection connection=(HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); if(connection.getResponseCode()==200){ InputStream inputStream=connection.getInputStream(); //呼叫工具類中的靜態方法 str=StreamToString.streamToStr(inputStream,"utf-8"); } } catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return str; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); //解析,封裝到bean,更新ui元件 icallbacks.updateUiByjson(s); } //定義一個介面 public interface Icallbacks{ /** * 根據回傳的json字串,解析並更新頁面元件 * @param jsonstr */ void updateUiByjson(String jsonstr); } }
//工具包
public class StreamToString { public static String streamToStr(InputStream inputStream,String chartSet){ StringBuilder builder=new StringBuilder(); try { BufferedReader br=new BufferedReader(new InputStreamReader(inputStream,chartSet)); String con; while ((con=br.readLine())!=null){ builder.append(con); } br.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return ""; } }
//呼叫工具包
public class MyAppaciton extends Application { @Override public void onCreate() { super.onCreate(); ImageloaderUtil.initConfig(this); } }
//activity-main
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ptr="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.day16.MainActivity"> <com.handmark.pulltorefresh.library.PullToRefreshListView android:id="@+id/pull_lv" ptr:ptrAnimationStyle="flip" ptr:ptrDrawable="@drawable/default_ptr_flip" ptr:ptrHeaderBackground="#383838" ptr:ptrHeaderTextColor="#FFFFFF" android:layout_width="match_parent" android:layout_height="match_parent"> </com.handmark.pulltorefresh.library.PullToRefreshListView> </RelativeLayout>
//item
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/img" android:src="@mipmap/ic_launcher" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv" android:textSize="25dp" android:text="1511" android:layout_marginLeft="20dp" /> </LinearLayout>
//加許可權
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
android:name=".MyAppaciton"