XListView实现网络加载图片和下拉刷新
本文实例为大家分享了XListView实现网络加载图片,和下拉刷新的功能,供大家参考,具体内容如下
MainActivity.java
public class MainActivity extends AppCompatActivity { private XListView contents; private int page = 0; private MyBaseAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contents = findViewById(R.id.contents); adapter = new MyBaseAdapter(getLayoutInflater()); contents.setAdapter(adapter); //是否开启下拉刷新 上拉加载 //contents.setPullRefreshEnable(false); contents.setPullLoadEnable(true); contents.setXListViewListener(new XListView.IXListViewListener() { @Override public void onRefresh() { page = 0; loadData(page); //加载刷新数据 } @Override public void onLoadMore() { loadData(page); } }); //一进来就去加载第一页数据 loadData(page); } private String url = "http://apis.juhe.cn/cook/query?key=3ec004200a6a2f4cf4774e480c006375&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn="; private void loadData(int page) { String requestUrlWithPageNum = url + page; //加载网络数据 new AsyncTask<String, Void, List<DataItem>>() { @Override protected List<DataItem> doInBackground(String... strings) { ResponseBean responseBean = null; try { URL url = new URL(strings[0]); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { String str = stream2String(urlConnection.getInputStream()); responseBean = new Gson().fromJson(str, ResponseBean.class); } else { // } return responseBean == null ? null : responseBean.getResult().getData(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(List<DataItem> dataItems) { if (dataItems == null) { Toast.makeText(MainActivity.this, "请求数据错误", Toast.LENGTH_LONG).show(); return; } //更新数据 updateData(dataItems); loadCompleted(); } }.execute(url); } private String stream2String(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()) { sb.append(tmp); } return sb.toString(); } private void updateData(List<DataItem> datas) { if (page == 0) { adapter.setDatas(datas); } else { adapter.addDatas(datas); } } //通过 加载 / 刷新 完成 private void loadCompleted() { //通过ListView:刷新、加载完成 page++; contents.stopLoadMore(); contents.stopRefresh(); } }
MyBaseAdapter.java
public class MyBaseAdapter extends BaseAdapter { private List<DataItem> mDatas; protected LayoutInflater mInflater; /** * 更新数据 */ public void setDatas(List<DataItem> datas) { mDatas.clear(); if (datas != null) { mDatas.addAll(datas); } notifyDataSetChanged(); } /** * 追加数据 */ public void addDatas(List<DataItem> datas) { if (datas != null) { mDatas.addAll(datas); notifyDataSetChanged(); } } public MyBaseAdapter(LayoutInflater mInflater) { this.mInflater = mInflater; mDatas = new ArrayList<>(); } @Override public int getCount() { return mDatas.size(); } @Override public DataItem getItem(int position) { return mDatas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { BaseViewHolder viewHolder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.item, parent, false); viewHolder = new BaseViewHolder(convertView); } else { viewHolder = (BaseViewHolder) convertView.getTag(); } viewHolder.bindData(getItem(position)); return convertView; } public class BaseViewHolder { private View itemView; private ImageView icon; private TextView title; private TextView date; public BaseViewHolder(View itemView) { this.itemView = itemView; title = itemView.findViewById(R.id.title); date = itemView.findViewById(R.id.date); icon = itemView.findViewById(R.id.icon); itemView.setTag(this); } public void bindData(DataItem dataItem) { title.setText(dataItem.getTitle()); date.setText(dataItem.getId()); ImageLoader.getInstance().displayImage(dataItem.getFirstImageUrl(), icon, ImageLoaderConfigs.getDefaultDisplayImageOptions(icon.getContext())); } } } ImageLoader.java public class ImageLoaderConfigs { public static ImageLoaderConfiguration getImageLoaderConfiguration(Context context) { ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(context) //内在缓存额外选项, 最大的宽度,高度 //.memoryCacheExtraOptions(480, 800) // default = device screen dimensions 内存缓存文件的最大长宽 //.diskCacheExtraOptions(480, 800, null) // 本地缓存的详细信息(缓存的最大长宽),最好不要设置这个 //线程池配置 //.taskExecutor() //.taskExecutorForCachedImages() //.threadPoolSize(3) // default 线程池内加载的数量 //.threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级 //任务处理优先级 Fist In Fist Out //.tasksProcessingOrder(QueueProcessingType.FIFO) // default //内存中不缓存一张图片的多个尺寸大小 //.denyCacheImageMultipleSizesInMemory() //内在缓存策略 //.memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现 //内存缓存大小 //.memoryCacheSize(2 * 1024 * 1024) // 内存缓存的最大值 //内在缓存大小:占用百分比 .memoryCacheSizePercentage(13) // default //磁盘缓存策略 //.diskCache(new LruDiskCache()) // default 可以自定义缓存路径 //磁盘缓存大小 .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值 //.diskCacheFileCount(100) // 可以缓存的文件数量 // default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密 //.diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) //.imageDownloader(new BaseImageDownloader(context)) // default //(new BaseImageDecoder(false)) // default //加载具体图片时的一些配置 .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default .writeDebugLogs() // 打印debug log .build(); return configuration; } public static DisplayImageOptions getDefaultDisplayImageOptions(Context context) { DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder() //是否缓存 .cacheInMemory(true) .cacheOnDisk(true) //RGB 565 r红色占5 g绿色占6 b蓝色占5 -> 2字节 //alpha //ARGB 4444 4 4 4 4 -> 2字节 //ARGB 8888 -> 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(new CircleBitmapDisplayer()) .build(); //ctrl + h //BitmapDisplayer; return displayImageOptions; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)