m使用RecyclerView
StaggeredGrid
(spanCount是变量)。每个GridItem(一个CardView
)包含一个方形ImageView。我想要的是从我的后端加载一个具有所需宽度和高度的图像,以完全适合CardView中的ImageView。有什么建议我能做到吗?代码示例如下:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
Picasso.with(context)
.load(String.format("http://mybackend.com/image/w_%d,h_%d/%s",
holder.image.getMeasuredWidth(), // This returns 0, but i want here a real width
holder.image.getMeasuredWidth(),
myCollection.get(position).getImagePid()))
.tag(context)
.placeholder(R.drawable.placeholder_logo)
.into(holder.image);
用2个单词:不知怎的,我需要在绑定ViewHolder之前获取imageView尺寸(宽度)。
答案 0 :(得分:1)
您是否考虑过使用.fit()?我相信这会调整图像的大小以完全适合ImageView。
答案 1 :(得分:0)
您可以使用ViewTreeObserver:
final int width = holder.image.getMeasuredWidth();
if (width > 0) {
Picasso.with(context)
.load(String.format("http://mybackend.com/image/w_%d,h_%d/%s",
holder.image.getMeasuredWidth(), // This returns 0, but i want here a real width
holder.image.getMeasuredWidth(),
myCollection.get(position).getImagePid()))
.tag(context)
.placeholder(R.drawable.placeholder_logo)
.into(holder.image);
} else {
holder.image.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
holder.image.getViewTreeObserver().removeGlobalOnLayoutListener(this);
Picasso.with(context)
.load(String.format("http://mybackend.com/image/w_%d,h_%d/%s",
holder.image.getMeasuredWidth(), // This returns 0, but i want here a real width
holder.image.getMeasuredWidth(),
myCollection.get(position).getImagePid()))
.tag(context)
.placeholder(R.drawable.placeholder_logo)
.into(holder.image);
}
});
}