我有一个帖子列表,其中大部分是图片(简单地说就是帖子,就像 G+ 或 FB 应用程序一样)。每个帖子条目都有一个图像纵横比,所以我可以根据图像的宽度设置图像高度,甚至在从服务器加载图像之前,这样卡片布局就不会在加载时发生变化。
问题是 layout_width="match_parent"
为卡片和帖子图像设置。当我获得 cardview 的宽度时,它为零。所以我无法计算高度。
目前我看到的唯一解决方案是采用父容器 (RecyclerView) 的宽度并扣除所有填充,但这看起来不是一个好的解决方案。
还有其他方法吗?
这里是适配器代码的例子
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
....
int width = holder.itemView.getWidth();
....
//do some calculations
}
布局(去掉不相关的部分)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardBackgroundColor="#ffffff"
card_view:cardCornerRadius="3dp">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="@+id/includedPost"
layout="@layout/post_details" />
</RelativeLayout>
</android.support.v7.widget.CardView>
包含的帖子:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/postImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/commenterImage"
android:minHeight="120dp"
android:scaleType="centerCrop" />
</RelativeLayout>
最佳答案
当 onBind
或 onViewAttachedToWindow
被调用时,子元素未被测量,因此您无法获得宽度。即使这些电话是在 child 测量完之后发出的,您尝试做的也不是一个好的做法,因为改变高度将需要重新测量。
如果您使用的是 LinearLayoutManager,它会将整个宽度提供给子项(期望 RecyclerView 填充和子项的边距)。从那里推导出你的高度不是很好但没问题。
另一种(更灵活的)方法是创建一个自定义的 ImageView 来保持纵横比。调用 onBind 时,您将设置自定义 ImageView 的所需纵横比。 调用 on measure 时,它将根据您的纵横比进行测量。
class MyImageView extends ImageVIew {
....
private float mScale = 1f;
public void setScale(int scale) {
mScale = scale;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
setMeasuredDimension(width, width * mScale);
}
}
因此,在您的 onBind 方法中,您根据您的 w/h 比率在 ImageView 上调用 setScale。
我还没有测试过,但这种方法应该可以正常工作。
关于android - 在 Adapter.onBindViewHolder 中获取 CardView 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26606094/