Я пытаюсь отобразить список песен, найденных на устройстве, запрашивая данные непосредственно из MediaStore. Я использую RecyclerView
и адаптер, который использует CursorAdapter
для получения данных из MediaStore. Когда вызывается адаптер onBindViewHolder
, запрос передается функции bindView
CursorAdapter
, все визуальные элементы установлены.Изображение мерцает при прокрутке в RecyclerView
public class ListRecyclerAdapter3 extends RecyclerView.Adapter<ListRecyclerAdapter3.SongViewHolder> {
// PATCH: Because RecyclerView.Adapter in its current form doesn't natively support
// cursors, we "wrap" a CursorAdapter that will do all teh job
// for us
public MediaStoreHelper mediaStoreHelper;
CustomCursorAdapter mCursorAdapter;
Context mContext;
public class SongViewHolder extends RecyclerView.ViewHolder {
public TextView textItemTitle;
public TextView textItemSub;
public ImageView imgArt;
public int position;
public String album_id;
public String path_art;
public String path_file;
public SongViewHolder(View v) {
super(v);
textItemTitle = (TextView) v.findViewById(R.id.textItemTitle);
textItemSub = (TextView) v.findViewById(R.id.textItemSub);
imgArt = (ImageView) v.findViewById(R.id.imgArt);
}
}
private class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public View newView(final Context context, Cursor cursor, ViewGroup parent) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.song_item, parent, false);
final SongViewHolder holder = new SongViewHolder(v);
v.setTag(holder);
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
SongViewHolder holder = (SongViewHolder) view.getTag();
holder.position = cursor.getPosition();
holder.textItemTitle.setText(cursor.getString(cursor.getColumnIndex("title")));
holder.textItemSub.setText(cursor.getString(cursor.getColumnIndex("artist")));
holder.album_id = cursor.getString(cursor.getColumnIndex("album_id"));
holder.path_file = cursor.getString(cursor.getColumnIndex("_data"));
Picasso.with(holder.imgArt.getContext())
.cancelRequest(holder.imgArt);
holder.imgArt.setImageDrawable(null);
new DownloadImageTask(mediaStoreHelper, context, holder.imgArt).execute(holder.album_id);
}
}
private class DownloadImageTask extends AsyncTask<String, String, String> {
private MediaStoreHelper mediaStoreHelper;
private ImageView imageView;
private Context context;
public DownloadImageTask(MediaStoreHelper mediaStoreHelper, Context context, ImageView imageView)
{
this.mediaStoreHelper = mediaStoreHelper;
this.context = context;
this.imageView = imageView;
}
@Override
protected String doInBackground(String... ids) {
return mediaStoreHelper.getAlbumArtPath(ids[0]);
}
protected void onPostExecute(String result) {
Picasso.with(context)
.load(new File(result))
.placeholder(R.drawable.ic_music)
.fit()
.into(imageView);
}
}
@Override
public void onBindViewHolder(SongViewHolder holder, int position) {
// Passing the binding operation to cursor loader
mCursorAdapter.getCursor().moveToPosition(position);
mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());
}
@Override
public SongViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Passing the inflater job to the cursor-adapter
View v = mCursorAdapter.newView(mContext, mCursorAdapter.getCursor(), parent);
return new SongViewHolder(v);
}
}
Проблемная часть загрузки изображения с состоит из двух частей:
- С ALBUMID я получил от
Cursor
, мне нужно использоватьContentResolver
, чтобы получить путь альбома файлов искусства - Загрузите изображение в поле
ImageView
, используя путь файла
T hese два прохода необходимо сделать в фоновом режиме, иначе прокрутка станет очень лаги. В функции bindView
я называюсь AsyncTask
делает работу, но проблема заключается в том, что при прокрутке быстро, несколько запросов изображений разработаны и это результат:
Как вы можете видеть из кода Я пытался отменить ожидающие запросы Пикассо по конкретному ImageView
, но этого недостаточно. Можно ли устранить эту проблему?
Я думаю, что вы можете включить прослушиватель Scroll в RecyclerView и только начать загрузку изображения, когда он прекратил прокрутку. – X3Btel
@ X3Btel хорошая мысль, я попробую – fillobotto