XListView Realizes Network Loading Picture and Drop down Refresh

  • 2021-10-24 23:48:09
  • OfStack

This article example for everyone to share XListView to achieve network loading pictures, and pull-down refresh function, for your reference, the specific content is as follows

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);

  // Whether to turn on drop-down refresh   Pull-up loading 
  //contents.setPullRefreshEnable(false);
  contents.setPullLoadEnable(true);

  contents.setXListViewListener(new XListView.IXListViewListener() {
   @Override public void onRefresh() {
    page = 0;
    loadData(page);
    // Load refresh data 
   }

   @Override public void onLoadMore() {
    loadData(page);
   }
  });

  //1 Come in and load the number 1 Page data 
  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;

  // Load network data 
  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, " Error in requesting data ", Toast.LENGTH_LONG).show();
     return;
    }

    // Update data 
    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);
  }
 }

 // Pass   Loading  /  Refresh   Finish 
 private void loadCompleted() {
  // Pass ListView Refresh, load complete 
  page++;
  contents.stopLoadMore();
  contents.stopRefresh();
 }
}

MyBaseAdapter.java


public class MyBaseAdapter extends BaseAdapter {

 private List<DataItem> mDatas;
 protected LayoutInflater mInflater;

 /**
  *  Update data 
  */
 public void setDatas(List<DataItem> datas) {
  mDatas.clear();
  if (datas != null) {
   mDatas.addAll(datas);
  }
  notifyDataSetChanged();
 }

 /**
  *  Append data 
  */
 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)
    // Internal cache extra options,   Maximum width, height 
    //.memoryCacheExtraOptions(480, 800) // default = device screen dimensions  Maximum length and width of memory cache files 
    //.diskCacheExtraOptions(480, 800, null) //  Details of local cache ( Maximum length and width of cache ) , it is best not to set this 
    // Thread pool configuration 
    //.taskExecutor()
    //.taskExecutorForCachedImages()
    //.threadPoolSize(3) // default  Number of loads in the thread pool 
    //.threadPriority(Thread.NORM_PRIORITY - 2) // default  Set the priority of the current thread 
    // Task processing priority  Fist In Fist Out
    //.tasksProcessingOrder(QueueProcessingType.FIFO) // default
    // Not cached in memory 1 Multiple sizes of a picture 
    //.denyCacheImageMultipleSizesInMemory()
    // Intrinsic caching strategy 
    //.memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // It can be implemented through its own memory cache 
    // Memory cache size 
    //.memoryCacheSize(2 * 1024 * 1024) //  Maximum value of memory cache 
    // Internal cache size: occupancy percentage 
    .memoryCacheSizePercentage(13) // default
    // Disk cache policy 
    //.diskCache(new LruDiskCache()) // default  You can customize the cache path 
    // Disk cache size 
    .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd Card ( Local ) Maximum cached value 
    //.diskCacheFileCount(100) //  Number of files that can be cached 
    // default For the use of HASHCODE Right UIL Encrypted naming,   You can also use MD5(new Md5FileNameGenerator()) Encryption 
    //.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
    //.imageDownloader(new BaseImageDownloader(context)) // default
    //(new BaseImageDecoder(false)) // default
    // When loading a specific picture, 1 Some configurations 
    .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
    .writeDebugLogs() //  Print debug log
    .build();

  return configuration;
 }

 public static DisplayImageOptions getDefaultDisplayImageOptions(Context context) {
  DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
    // Whether to cache 
    .cacheInMemory(true)
    .cacheOnDisk(true)
    //RGB 565  r Red accounts for 5  g Green account 6  b Blue 5 -> 2 Byte 
    //alpha
    //ARGB 4444  4 4 4 4 -> 2 Byte 
    //ARGB 8888  -> 4 Byte 

    //10 * 10  Use rgb565 -> 10*10*2

    .bitmapConfig(Bitmap.Config.RGB_565)
    // When loading, what is displayed when loading errors 
    .showImageOnLoading(R.mipmap.ic_launcher)
    .showImageOnFail(R.mipmap.ic_launcher)
    //
    .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)

    // Loading effect 
    //ctrl + p
    .displayer(new CircleBitmapDisplayer())
    .build();

  //ctrl + h
  //BitmapDisplayer;
  return displayImageOptions;
 }
}

Related articles: