加载图片
ImageView
要将指定 URL,Uri,资源 ID 或任何其他模型中的图像加载到 ImageView
:
ImageView imageView = (ImageView) findViewById(R.id.imageView);
String yourUrl = "http://www.yoururl.com/image.png";
Glide.with(context)
.load(yourUrl)
.into(imageView);
对于 Uris,用你的 Uri(content://media/external/images/1
)替换 yourUrl
。对于 Drawables,将 yourUrl
替换为你的资源 ID(R.drawable.image
)。
RecyclerView 和 ListView
在 ListView 或 RecyclerView 中,你可以使用完全相同的行:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
MyViewHolder myViewHolder = (MyViewHolder) viewHolder;
String currentUrl = myUrls.get(position);
Glide.with(context)
.load(currentUrl)
.into(myViewHolder.imageView);
}
如果你不想在 onBindViewHolder
中开始加载,请确保在修改 ImageView
之前你可以管理任何 ImageView
Glide:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
MyViewHolder myViewHolder = (MyViewHolder) viewHolder;
String currentUrl = myUrls.get(position);
if (TextUtils.isEmpty(currentUrl)) {
Glide.clear(viewHolder.imageView);
// Now that the view has been cleared, you can safely set your own resource
viewHolder.imageView.setImageResource(R.drawable.missing_image);
} else {
Glide.with(context)
.load(currentUrl)
.into(myViewHolder.imageView);
}
}