我有一個帖子列表,其中大部分是圖片(簡單地說就是像G +或FB應用程序一樣的帖子)。每個帖子條目都有一個圖像寬高比,所以即使在圖像從服務器加載之前,我也可以根據它的寬度來設置圖像高度,因此卡片佈局在加載時不會改變。獲取CardView在Adapter.onBindViewHolder中的寬度
的問題是兩個卡後的圖像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>
includedPost:
<?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>
你可以把你調用getWidth方法的一部分代碼(結果爲0)嗎? – 2014-10-28 10:46:55
更新我的示例代碼 – Andrew 2014-10-28 11:04:20
問題也許你可以嘗試調用的getWidth()在[onViewAttachedToWindow]法(https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#onViewAttachedToWindow (VH))根據文檔:「這可以作爲一個合理的信號,該視圖即將被用戶看到」 – 2014-10-28 11:12:16