ListView的图片可以通过Adapter来添加。具体步骤如下:
示例代码如下:
public class MyAdapter extends BaseAdapter {
private Context mContext;
private List<Integer> mImageList;
public MyAdapter(Context context, List<Integer> imageList) {
mContext = context;
mImageList = imageList;
}
@Override
public int getCount() {
return mImageList.size();
}
@Override
public Object getItem(int position) {
return mImageList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = LayoutInflater.from(mContext).inflate(R.layout.list_item_layout, parent, false);
ImageView imageView = view.findViewById(R.id.image_view);
imageView.setImageResource(mImageList.get(position));
return view;
}
}
然后,在Activity或Fragment中,创建ListView,并设置Adapter:
ListView listView = findViewById(R.id.list_view);
List<Integer> imageList = new ArrayList<>();
imageList.add(R.drawable.image1);
imageList.add(R.drawable.image2);
imageList.add(R.drawable.image3);
MyAdapter adapter = new MyAdapter(this, imageList);
listView.setAdapter(adapter);
以上代码示例假设已经定义了一个list_item_layout布局文件,其中包含一个ImageView控件(id为image_view)。
注意:在实际使用中,可以根据自己的需求进行适当的修改和优化。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: android listView排序问题