Search code examples
androidandroid-recyclerviewandroid-linearlayout

Item views are not measured correctly when recycled in the RecyclerView


I have a scenario where, when views are recycled, the layout is incorrect. My row item layouts are as follows (note the wrap_content LinearLayout width, weight, and ellipsize):

     <LinearLayout
          android:id="@+id/header"
          android:layout_width="wrap_content"       
          android:layout_height="wrap_content"    
          android:orientation="horizontal"
          >
        <TextView
            android:id="@+id/text1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"               
            android:ellipsize="middle"
            android:singleLine="true"
            tools:text="Ann really freaking long last name Droid"
            />
        <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <TextView
            android:id="@+id/text3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
      </LinearLayout>

Desired behavior

    row1 | 1-short-text | 2-text | 3-more-text
    ----------------------------------------------------
    row2 | 1-short-text | 2-text | 3-more-text
    ----------------------------------------------------
    row3 | 1-long-ellipsiz...text | 2-text | 3-more-text
    ----------------------------------------------------
    row4 | 1-tiny | 2-text-longer | 3-more-text-blah
    ----------------------------------------------------

Actual behavior

    row1 | 1-...et | 2-text | 3-more-text     <-- ellipsized unnecessarily
    ----------------------------------------------------
    row4 | 1-short-text | 2-text | 3-more-text
    ----------------------------------------------------
    row2 | 1-long-ellipsiz...text | 2-text | 3-more-text
    ----------------------------------------------------
    row3 | 1-tiny |    2-text-longer | 3-more-text-blah  <-- spacing
    ----------------------------------------------------

What's the best way to go about solving this layout issue? Note: it works fine in a 4.1.1 emulator.


Solution

  • There's a known issue where TextViews don't re-measure in this scenario. I was able to solve this by doing the following when setting the data in my ViewHolder:

    text1.setText("some-dynamic-text");
    text1.requestLayout();  // <-- This is key... requestLayout after setting text.
    

    When the view is recycled and new text was set, it wasn't laying out properly. Explicitly asking it to re-layout seems to re-calculate properly.