Android studio中glide怎么在listview中加载图片
时间: 2024-05-29 07:11:43 浏览: 188
在Android Studio中使用Glide加载图片到ListView中,需要遵循以下步骤:
1. 添加Glide依赖项
在项目的build.gradle文件中添加以下依赖项:
```
dependencies {
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
```
2. 创建ListView的Adapter
创建一个继承BaseAdapter的Adapter类,并实现getView()方法。在getView()方法中使用Glide加载图片。
```java
public class MyAdapter extends BaseAdapter {
private Context context;
private List<String> imageUrlList;
public MyAdapter(Context context, List<String> imageUrlList) {
this.context = context;
this.imageUrlList = imageUrlList;
}
@Override
public int getCount() {
return imageUrlList.size();
}
@Override
public Object getItem(int position) {
return imageUrlList.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) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false);
viewHolder = new ViewHolder();
viewHolder.imageView = convertView.findViewById(R.id.imageView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Glide.with(context)
.load(imageUrlList.get(position))
.into(viewHolder.imageView);
return convertView;
}
static class ViewHolder {
ImageView imageView;
}
}
```
3. 设置ListView的Adapter
在Activity或Fragment中创建ListView并设置Adapter。
```java
public class MyActivity extends AppCompatActivity {
private ListView listView;
private MyAdapter adapter;
private List<String> imageUrlList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
listView = findViewById(R.id.listView);
imageUrlList = new ArrayList<>();
imageUrlList.add("https://example.com/image1.jpg");
imageUrlList.add("https://example.com/image2.jpg");
imageUrlList.add("https://example.com/image3.jpg");
adapter = new MyAdapter(this, imageUrlList);
listView.setAdapter(adapter);
}
}
```
以上就是在Android Studio中使用Glide加载图片到ListView中的步骤。
阅读全文