XListView实现网络加载图片和下拉刷新
本文实例为大家分享了XListView实现网络加载图片,和下拉刷新的功能,供大家参考,具体内容如下
MainActivity.java
publicclassMainActivityextendsAppCompatActivity{ privateXListViewcontents; privateintpage=0; privateMyBaseAdapteradapter; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contents=findViewById(R.id.contents); adapter=newMyBaseAdapter(getLayoutInflater()); contents.setAdapter(adapter); //是否开启下拉刷新上拉加载 //contents.setPullRefreshEnable(false); contents.setPullLoadEnable(true); contents.setXListViewListener(newXListView.IXListViewListener(){ @OverridepublicvoidonRefresh(){ page=0; loadData(page); //加载刷新数据 } @OverridepublicvoidonLoadMore(){ loadData(page); } }); //一进来就去加载第一页数据 loadData(page); } privateStringurl= "http://apis.juhe.cn/cook/query?key=3ec004200a6a2f4cf4774e480c006375&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn="; privatevoidloadData(intpage){ StringrequestUrlWithPageNum=url+page; //加载网络数据 newAsyncTask>(){ @OverrideprotectedList doInBackground(String...strings){ ResponseBeanresponseBean=null; try{ URLurl=newURL(strings[0]); HttpURLConnectionurlConnection=(HttpURLConnection)url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); intresponseCode=urlConnection.getResponseCode(); if(responseCode==200){ Stringstr=stream2String(urlConnection.getInputStream()); responseBean=newGson().fromJson(str,ResponseBean.class); }else{ // } returnresponseBean==null?null:responseBean.getResult().getData(); }catch(MalformedURLExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } returnnull; } @OverrideprotectedvoidonPostExecute(List dataItems){ if(dataItems==null){ Toast.makeText(MainActivity.this,"请求数据错误",Toast.LENGTH_LONG).show(); return; } //更新数据 updateData(dataItems); loadCompleted(); } }.execute(url); } privateStringstream2String(InputStreamis)throwsIOException{ BufferedReaderbr=newBufferedReader(newInputStreamReader(is)); StringBuildersb=newStringBuilder(); for(Stringtmp=br.readLine();tmp!=null;tmp=br.readLine()){ sb.append(tmp); } returnsb.toString(); } privatevoidupdateData(List datas){ if(page==0){ adapter.setDatas(datas); }else{ adapter.addDatas(datas); } } //通过加载/刷新完成 privatevoidloadCompleted(){ //通过ListView:刷新、加载完成 page++; contents.stopLoadMore(); contents.stopRefresh(); } }
MyBaseAdapter.java
publicclassMyBaseAdapterextendsBaseAdapter{ privateListmDatas; protectedLayoutInflatermInflater; /** *更新数据 */ publicvoidsetDatas(List datas){ mDatas.clear(); if(datas!=null){ mDatas.addAll(datas); } notifyDataSetChanged(); } /** *追加数据 */ publicvoidaddDatas(List datas){ if(datas!=null){ mDatas.addAll(datas); notifyDataSetChanged(); } } publicMyBaseAdapter(LayoutInflatermInflater){ this.mInflater=mInflater; mDatas=newArrayList<>(); } @OverridepublicintgetCount(){ returnmDatas.size(); } @OverridepublicDataItemgetItem(intposition){ returnmDatas.get(position); } @OverridepubliclonggetItemId(intposition){ returnposition; } @OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){ BaseViewHolderviewHolder=null; if(convertView==null){ convertView=mInflater.inflate(R.layout.item,parent,false); viewHolder=newBaseViewHolder(convertView); }else{ viewHolder=(BaseViewHolder)convertView.getTag(); } viewHolder.bindData(getItem(position)); returnconvertView; } publicclassBaseViewHolder{ privateViewitemView; privateImageViewicon; privateTextViewtitle; privateTextViewdate; publicBaseViewHolder(ViewitemView){ this.itemView=itemView; title=itemView.findViewById(R.id.title); date=itemView.findViewById(R.id.date); icon=itemView.findViewById(R.id.icon); itemView.setTag(this); } publicvoidbindData(DataItemdataItem){ title.setText(dataItem.getTitle()); date.setText(dataItem.getId()); ImageLoader.getInstance().displayImage(dataItem.getFirstImageUrl(),icon, ImageLoaderConfigs.getDefaultDisplayImageOptions(icon.getContext())); } } } ImageLoader.java publicclassImageLoaderConfigs{ publicstaticImageLoaderConfigurationgetImageLoaderConfiguration(Contextcontext){ ImageLoaderConfigurationconfiguration=newImageLoaderConfiguration.Builder(context) //内在缓存额外选项,最大的宽度,高度 //.memoryCacheExtraOptions(480,800)//default=devicescreendimensions内存缓存文件的最大长宽 //.diskCacheExtraOptions(480,800,null)//本地缓存的详细信息(缓存的最大长宽),最好不要设置这个 //线程池配置 //.taskExecutor() //.taskExecutorForCachedImages() //.threadPoolSize(3)//default线程池内加载的数量 //.threadPriority(Thread.NORM_PRIORITY-2)//default设置当前线程的优先级 //任务处理优先级FistInFistOut //.tasksProcessingOrder(QueueProcessingType.FIFO)//default //内存中不缓存一张图片的多个尺寸大小 //.denyCacheImageMultipleSizesInMemory() //内在缓存策略 //.memoryCache(newLruMemoryCache(2*1024*1024))//可以通过自己的内存缓存实现 //内存缓存大小 //.memoryCacheSize(2*1024*1024)//内存缓存的最大值 //内在缓存大小:占用百分比 .memoryCacheSizePercentage(13)//default //磁盘缓存策略 //.diskCache(newLruDiskCache())//default可以自定义缓存路径 //磁盘缓存大小 .diskCacheSize(50*1024*1024)//50Mbsd卡(本地)缓存的最大值 //.diskCacheFileCount(100)//可以缓存的文件数量 //default为使用HASHCODE对UIL进行加密命名,还可以用MD5(newMd5FileNameGenerator())加密 //.diskCacheFileNameGenerator(newHashCodeFileNameGenerator()) //.imageDownloader(newBaseImageDownloader(context))//default //(newBaseImageDecoder(false))//default //加载具体图片时的一些配置 .defaultDisplayImageOptions(DisplayImageOptions.createSimple())//default .writeDebugLogs()//打印debuglog .build(); returnconfiguration; } publicstaticDisplayImageOptionsgetDefaultDisplayImageOptions(Contextcontext){ DisplayImageOptionsdisplayImageOptions=newDisplayImageOptions.Builder() //是否缓存 .cacheInMemory(true) .cacheOnDisk(true) //RGB565r红色占5g绿色占6b蓝色占5->2字节 //alpha //ARGB44444444->2字节 //ARGB8888->4字节 //10*10用rgb565->10*10*2 .bitmapConfig(Bitmap.Config.RGB_565) //加载时、加载错误时展示什么内容 .showImageOnLoading(R.mipmap.ic_launcher) .showImageOnFail(R.mipmap.ic_launcher) // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) //加载效果 //ctrl+p .displayer(newCircleBitmapDisplayer()) .build(); //ctrl+h //BitmapDisplayer; returndisplayImageOptions; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。