最好的方法是使用异步任务。
在后台,你将加载图像,在post execute中,你将用图像填充不同的视图,我在我的项目中使用这个,滚动非常平滑,就像在后台滚动一样,它将开始填充视图
看一看,我用这个来平滑地填充图像
private class CargarImg extends AsyncTask<Void, Void, Void> {
private final int mPosition;
private final MyViewHolder mHolder;
private String mStringTexto;
private Drawable mDrawableIcono;
public CargarImg(int position, MyViewHolder holder) {
mPosition = position;
mHolder = holder;
}
@Override
protected Void doInBackground(Void... voids) {
Bitmap mBitmap;
try{
mStringTexto = json.getNombre(mArrayData.get(mPosition));
mDrawableIcono= json.getIcono(mArrayData.get(mPosition));
mBitmap = ThumbnailUtils.extractThumbnail(((BitmapDrawable)mDrawableIcono).getBitmap(),150,150);
mDrawableIcono = new BitmapDrawable(mContext.getResources(), mBitmap);
}catch (Exception e){
somethingHappened(mContext, "can't reach the photo");
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mHolder.build(mStringTexto,mDrawableIcono);
mHolder.imageView.setBackgroundColor(cargarColor(json.getTipo(mArrayData.get(mPosition))));
}
}
正如你所看到的,我在滚动的时候加载图像,所以,由于我不是一次加载所有的图像,它不会冻结ui线程,你可以滚动,图像也会加载,这只是我的代码给你的一个提示,但我真的建议你使用asynctask。
这是我的
bindViewHolder
和
viewHolder
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(mLayoutResourceId, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
new CargarImg(position,holder).execute(); //here i execute the async to load the images smoothly
}
再多一点:
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView letterText;
public ImageView imageView;
private MyViewHolder(View view) {
super(view);
letterText = view.findViewById(R.id.grid_text);
imageView = view.findViewById(R.id.grid_image);
}
void build(String title, Drawable dr) {
letterText.setText(title);
imageView.setImageDrawable(dr);
}
}
这基本上就是您需要加载图像的所有适配器。