异步下载图片的最佳位置是什么?我在带有viewholder的自定义适配器中执行此操作。
public class PostsAdapter extends BaseAdapter {
private static final String TAG = "tag.example.tag";
private static final String URL_PREFIX = "http://someapi.com/v1/api/";
private Context mContext;
private ArrayList<Post> mData;
private static LayoutInflater inflater = null;
public PostsAdapter(Context context, ArrayList<Post> data) {
mContext = context;
mData = data;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
}
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ViewHolder holder = null;
if(view == null)
v = inflater.inflate(R.layout.post_listviewrow, null);
holder = new ViewHolder();
holder.imageView = (ImageView) v.findViewById(R.id.imageView);
Post post = (Post) mData.get(i);
// Download image with Picasso
holder.imageView.setTag(post.getPictureUrl());
Picasso.with(mContext).load(URL_PREFIX + post.getPictureUrl()).into(holder.imageView);
return v;
}
static class ViewHolder {
TextView titleTextView;
ImageView imageView;
}
}
答案 0 :(得分:1)
解: 将getView方法更改为此类
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
if(view == null) {
view = inflater.inflate(R.layout.post_listviewrow, null);
holder = new ViewHolder();
holder.imageView = (ImageView) view.findViewById(R.id.imageView);
holder.titleTextView = (TextView) view.findViewById(R.id.textview);
holder.progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Get position
Post post = (Post) mData.get(i);
holder.titleTextView.setText(post.getTitle());
Picasso picasso = Picasso.with(mContext);
picasso.setIndicatorsEnabled(true);
holder.progressBar.setVisibility(View.VISIBLE);
picasso.load(URL_PREFIX + post.getPictureUrl())
.placeholder(R.drawable.placeholder)
.fit()
.centerCrop()
.into(holder.imageView, new Callback() {
@Override
public void onSuccess() {
holder.progressBar.setVisibility(View.GONE);
}
@Override
public void onError() {}
});
return view;
}
static class ViewHolder {
TextView titleTextView;
ImageView imageView;
ProgressBar progressBar;
}
无论如何,您认为适配器是放置下载任务的正确位置吗?