将 listview 适配器更改为回收器视图适配器
Posted
技术标签:
【中文标题】将 listview 适配器更改为回收器视图适配器【英文标题】:Change listview adapter to recycler view adapter 【发布时间】:2016-04-05 15:49:16 【问题描述】:当我将图像从 SD 卡加载到 ListView 时,它开始滞后。我不能流畅地滚动。所以,我决定使用回收站视图,也许还有毕加索。我面临的唯一问题是,ListView 适配器无法与 RecyclerView 一起使用。
如何重写以下代码/适配器以使用 RecyclerView?
万事如意,新年快乐!
public class Saveditems extends BaseActivity
ArrayList<String> f = new ArrayList<>();// list of file paths
File[] listFile;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.saveditems);
activateToolbarWithHomeEnabled().setNavigationOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
finish();
);
getFromSdcard();
RecyclerView imagelist = (RecyclerView) findViewById(R.id.PhoneImageGrid);
ImageAdapter imageAdapter = new ImageAdapter();
imagelist.setAdapter(imageAdapter); //error
//image adapter cannot be applied to recycler view
public void getFromSdcard()
File file = new File(Environment.getExternalStorageDirectory() + "/FlickrBrowser");
if (file.isDirectory())
listFile = file.listFiles();
for (File aListFile : listFile)
f.add(aListFile.getAbsolutePath());
public class ImageAdapter extends BaseAdapter
private LayoutInflater mInflater;
public ImageAdapter()
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
public int getCount()
return f.size();
public Object getItem(int position)
return position;
public long getItemId(int position)
return position;
@SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent)
ViewHolder holder;
if (convertView == null)
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
else
holder = (ViewHolder) convertView.getTag();
Bitmap myBitmap = BitmapFactory.decodeFile(f.get(position));
holder.imageview.setImageBitmap(myBitmap);
return convertView;
class ViewHolder
ImageView imageview;
【问题讨论】:
【参考方案1】:public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageHolder>
List<String> f;
public ImageAdapter(List<String> list)
f=list;
@Override
public ImageHolder onCreateViewHolder(ViewGroup parent, int viewType)
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.yourlayout, parent, false);
return new ImageHolder(v);
@Override
public void onBindViewHolder(final ImageHolder holder, final int position)
Bitmap myBitmap = BitmapFactory.decodeFile(f.get(position));
holder.imageview.setImageBitmap(myBitmap);
public static class ImageHolder extends RecyclerView.ViewHolder
ImageView imageview;
public ImageHolder(View itemView)
super(itemView);
imageview=(ImageView)itemView.findViewById(R.id.yourimageid)
【讨论】:
不幸的是,我无法让它工作。 ImageAdapter 中未定义数组列表“f”。 将其传递给 imageadapter 构造函数 我很感激!谢谢,我试试看。以上是关于将 listview 适配器更改为回收器视图适配器的主要内容,如果未能解决你的问题,请参考以下文章
Android中通过数组资源文件xml与适配器两种方式给ListView列表视图设置数据源