ListView的圖片可以通過(guò)Adapter來(lái)添加。具體步驟如下:
示例代碼如下:
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中,創(chuàng)建ListView,并設(shè)置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);
以上代碼示例假設(shè)已經(jīng)定義了一個(gè)list_item_layout布局文件,其中包含一個(gè)ImageView控件(id為image_view)。
注意:在實(shí)際使用中,可以根據(jù)自己的需求進(jìn)行適當(dāng)?shù)男薷暮蛢?yōu)化。