我有一个帖子列表,其中大部分都是图片(简单地说它就像G或FB应用程序一样).每个帖子条目都有一个图像宽高比,所以我甚至可以在从服务器加载图像之前根据它的宽度设置图像高度,因此卡片布局在加载时不会改变.
问题是为card和post图像设置layout_width =“match_parent”.当我获得cardview的宽度时,它为零.所以我无法计算身高.
现在,我看到的唯一解决方案是获取父容器的宽度(RecyclerView)并扣除所有填充,但它看起来不是一个好的解决方案.
还有其他办法吗?
以下是适配器代码的示例
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
....
int width = holder.itemView.getWidth();
....
//do some calculations
}
布局(没有不相关的部分)
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">
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:id="@+id/includedPost"
layout="@layout/post_details" />
includedPost:
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
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" />