要在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));
來設置每個列表項的圖片。