android获取view的宽度,android – 在Adapter.onBindViewHolder中获取CardView的宽度

在Android应用中,为实现类似Facebook或Instagram的帖子列表,需要根据图片的宽度设置其高度以保持宽高比。然而,在Adapter的onBindViewHolder方法中,直接获取CardView的宽度返回为0。本文探讨了如何在布局加载完成前正确获取宽度,以便计算并设置ImageView的高度,避免在加载图片时改变卡片布局的尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我有一个帖子列表,其中大部分都是图片(简单地说它就像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" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值