Ho un elenco di post e la maggior parte di essi sono immagini (in altre parole si tratta di post come app G + o FB). Ogni voce post ha uno aspect ratio dell'immagine, quindi posso impostare l'altezza dell'immagine in base alla sua larghezza anche prima che l'immagine sia stata caricata dal server, quindi il layout delle carte non cambierebbe sul carico.Ottieni la larghezza di CardView in Adapter.onBindViewHolder
Il problema è layout_width="match_parent"
impostato per la carta e l'immagine post. Quando ottengo la larghezza di cardview è zero. Quindi non posso calcolare l'altezza.
Per ora l'unica soluzione che vedo è quella di prendere la larghezza del contenitore padre (RecyclerView) e dedurre tutti i paddings, ma non sembra una buona soluzione.
C'è un altro modo per farlo?
Ecco un esempio di codice di adattatore
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
....
int width = holder.itemView.getWidth();
....
//do some calculations
}
Layout (senza parti irrilevanti)
<?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>
Puoi inserire parte del codice in cui chiami il metodo getWidth (con un risultato 0)? –
Ho aggiornato la mia domanda con il codice di esempio – Andrew
Forse potresti provare a chiamare il metodo getWidth() in [onViewAttachedToWindow] (https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#onViewAttachedToWindow (VH)) secondo il documento: "Questo può essere usato come un segnale ragionevole che la vista sta per essere vista dall'utente" –