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)。
注意:在實際使用中,可以根據自己的需求進行適當的修改和優化。