listview控件怎么添加图片

1822
2023/6/16 21:43:04
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在ListView控件中添加图片,可以使用自定义的适配器(Adapter)来实现。以下是一种常用的方法:

  1. 创建一个自定义的适配器类,继承自BaseAdapter类,并实现必要的方法。
public class MyAdapter extends BaseAdapter {
private Context mContext;
private List<String> mDataList;
private List<Integer> mImageList;
public MyAdapter(Context context, List<String> dataList, List<Integer> imageList) {
mContext = context;
mDataList = dataList;
mImageList = imageList;
}
@Override
public int getCount() {
return mDataList.size();
}
@Override
public Object getItem(int position) {
return mDataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.list_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.textView = convertView.findViewById(R.id.text_view);
viewHolder.imageView = convertView.findViewById(R.id.image_view);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(mDataList.get(position));
viewHolder.imageView.setImageResource(mImageList.get(position));
return convertView;
}
private static class ViewHolder {
TextView textView;
ImageView imageView;
}
}
  1. 在布局文件中,定义ListView控件和每个列表项的布局。
<!-- activity_main.xml -->
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- list_item.xml -->
<LinearLayout
...
android:orientation="horizontal">
<ImageView
android:id="@+id/image_view"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
  1. 在Activity中,使用自定义的适配器来设置ListView的数据源。
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private MyAdapter mAdapter;
private List<String> mDataList;
private List<Integer> mImageList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.list_view);
mDataList = new ArrayList<>();
mDataList.add("Item 1");
mDataList.add("Item 2");
mDataList.add("Item 3");
mImageList = new ArrayList<>();
mImageList.add(R.drawable.image1);
mImageList.add(R.drawable.image2);
mImageList.add(R.drawable.image3);
mAdapter = new MyAdapter(this, mDataList, mImageList);
mListView.setAdapter(mAdapter);
}
}

在上述代码中,假设有三个图片资源分别为image1image2image3,通过mImageList来存储图片资源的ID。在适配器的getView()方法中,通过viewHolder.imageView.setImageResource(mImageList.get(position));来设置每个列表项的图片。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: listview怎么异步加载数据