要在ListView控件中添加图片,可以使用自定义的适配器(Adapter)来实现。以下是一种常用的方法:
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;
}
}
<!-- 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>
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);
}
}
在上述代码中,假设有三个图片资源分别为image1
、image2
和image3
,通过mImageList
来存储图片资源的ID。在适配器的getView()
方法中,通过viewHolder.imageView.setImageResource(mImageList.get(position));
来设置每个列表项的图片。