В настоящее время я сталкиваюсь со следующей проблемой - я создаю пользовательский ListView ( 1 x ImageView + 2 x TextView).Он отображает контент из I-net, который является XML файлом.
Что я делаю - я использую AsyncTask для фонового запуска процесса загрузки XML содержимое и заполнение ListView путем вызова publishProgress (...) метода для каждого элемента списка из doInBackground (...) метод.Когда doInBackground (...) завершится, я уже собрал URL каждого изображения, которое я хочу отобразить, а затем из onPostExecute (...) метод Я запускаю процесс загрузки изображений и обновляю UI для каждого загруженного изображения.Проблема для меня заключается в том, что ListView должен заполнить хотя бы несколько элементов, прежде чем начать загрузку нарисованного файла и обновить список.В настоящее время ListView показывает один элемент, и при заполнении следующего, все изображения уже загружены.Я отладил приложение и увидел, что остановился в методе onPostExecute (...) и хочу взять количество элементов ListView , он просто возвращаетсяодин, как он отображает.
Есть ли способ вызвать появление элементов Listview , прежде чем начать загрузку, или это, потому что у меня есть подключение к I-net, которое у меня естьДостаточно и нет задержки при загрузке изображений.
Я забыл только упомянуть, что каждое изображение не больше 10 КБ.
Это мой пользовательский AsyncTask :
private class DownloadFilesTask extends AsyncTask<String, Object, List<RSSItem>> {
protected void onPreExecute() {
super.onPreExecute();
la.clear();
}
protected List<RSSItem> doInBackground(String... urls) {
parse(urls[0]);
if (feed == null) { return null; }
rssList = feed.getAllItems();
Iterator<RSSItem> iterator = rssList.iterator();
while(iterator.hasNext()) {
if (isCancelled()) return null;
RSSItem rss = iterator.next();
publishProgress(rss);
}
return rssList;
}
protected void onProgressUpdate(Object... progress) {
super.onProgressUpdate(progress);
la.add((RSSItem)progress[0]);
la.notifyDataSetChanged();
}
protected void onPostExecute(List<RSSItem> result) {
super.onPostExecute(result);
Drawable downloadedImage;
for (int z = 0; z < rssList.size(); z++) {
downloadedImage = downloadImage(rssList.get(z).getImageURL());
((RSSItem)rssList.get(z)).setImage(downloadedImage);
la.notifyDataSetChanged();
}
}
protected void onCancelled() {
super.onCancelled();
}
}
Вот пользовательский Listadapter :
private class ListAdapter extends ArrayAdapter<RSSItem> {
private List<RSSItem> items;
public ListAdapter(Context context, int textViewResourceId, List<RSSItem> items) {
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
RSSItem item = items.get(position);
if (item != null) {
ImageView itemImage = (ImageView) v.findViewById(R.id.ivImage);
TextView title = (TextView) v.findViewById(R.id.tvTitle);
TextView description = (TextView) v.findViewById(R.id.tvDescription);
if (item.getImage() != null) {
itemImage.setBackgroundDrawable(item.getImage());
} else {
itemImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon));
}
if (title != null) {
title.setText(item.getTitle());
}
if (description != null) {
description.setText(item.getDescription());
}
}
return v;
}
}
... и Item class:
public class RSSItem {
private String data = null;
private String description = null;
private Drawable image = null;
private String imageUrl = null;
private String title = null;
RSSItem() {
}
public void setData(String data) {
this.data = data;
}
public void setDescription(String description) {
this.description = description;
}
public void setImageURL(String imageURL) {
this.imageUrl = imageURL;
}
public void setImage(Drawable image) {
this.image = image;
}
public void setTitle(String title) {
this.title = title;
}
public String getData() {
return data;
}
public String getDescription() {
return description;
}
public Drawable getImage() {
return image;
}
public String getImageURL() {
return imageUrl;
}
public String getTitle() {
return title;
}
}
@ ИЗМЕНЕНИЯ:
закрытый класс DownloadFilesTask расширяет AsyncTask> {protected void onPreExecute () {super.onPreExecute ();
la.clear();
}
protected List<RSSItem> doInBackground(String... urls) {
parse(urls[0]);
if (feed == null) { return null; }
rssList = feed.getAllItems();
publishProgress(true);
Drawable downloadedImage;
for (int z = 0; z < rssList.size(); z++) {
downloadedImage = downloadImage(rssList.get(z).getImageURL());
((RSSItem)rssList.get(z)).setImage(downloadedImage);
}
return rssList;
}
protected void onProgressUpdate(Object... progress) {
super.onProgressUpdate(progress);
la.notifyDataSetChanged();
}
protected void onPostExecute(List<RSSItem> result) {
super.onPostExecute(result);
la.notifyDataSetChanged();
}
protected void onCancelled() {
super.onCancelled();
}
}