在RecyclerView中回收时,项目视图未正确测量 [英] Item views are not measured correctly when recycled in the RecyclerView
问题描述
我有一个场景,当回收视图时,布局不正确.我的行项目布局如下(请注意wrap_content
LinearLayout宽度,weight
和ellipsize
):
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>
期望的行为
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
----------------------------------------------------
实际行为
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
----------------------------------------------------
解决此布局问题的最佳方法是什么?注意:它在4.1.1模拟器中可以正常工作.
What's the best way to go about solving this layout issue? Note: it works fine in a 4.1.1 emulator.
推荐答案
存在一个已知问题,在这种情况下TextViews不会重新测量.通过在ViewHolder中设置数据,我可以通过执行以下操作来解决此问题:
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.
这篇关于在RecyclerView中回收时,项目视图未正确测量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!