在RecyclerView中具有最大宽度的简单约束布局子项

3

我正在尝试创建一个 TextView,使其在达到最大宽度之前自动换行。下面的代码完美地实现了这一点,但当它在 RecyclerView 中使用时却不起作用。似乎 TextViewonBindViewHolder() 中更改文本后不会重新测量其宽度。

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/message"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_max="wrap"
        app:layout_constraintWidth_default="percent"
        app:layout_constraintWidth_percent="0.72" />

</androidx.constraintlayout.widget.ConstraintLayout>

enter image description here




然而请注意,如果在下面的onBindViewHolder()中在TextView上调用requestLayout(),它可以正常工作:

更新:onBindViewHolder()中使用以下代码也可以正常工作。

ConstraintSet().apply {
    clone(holder.parent)
    applyTo(holder.parent)
}

父布局为ConstraintLayout

enter image description here

有人能理解这里发生了什么吗?这是ConstraintLayout的一个bug吗?在onBindViewHolder()中调用requestLayout()是一种不好的做法,我不想这样做。


删除 app:layout_constraintWidth_max="wrap",它将采用指定的宽度,即 app:layout_constraintWidth_percent="0.72" - Zulqarnain
我希望它首先进行换行,直到达到最大宽度。 - M-Wajeeh
将您的TextView放入FrameLayout中。并将“app:layout_constraintWidth_max =”wrap“”更改为“app:layout_constraintWidth_default =”wrap“” 如果不使用Framelayout使用“app:layout_constraintWidth_default”,则无法进行省略。 - Joris
3个回答

1
我知道已经过去一个月了,但最近我遇到了这个问题,也找不到答案。作者提出的改变ConstraintSet()的方法有效,但一直有一个问题,那就是这种方法是否高效。另一种解决方法是将app:layout_constraintWidth_max="wrap"更改为app:layout_constraintWidth_default="wrap"。这对我有用,当回收视图持有者时,recyclerView会正确更新约束条件。

这对我有效。我将包装值替换为我想要的度量值。 - ganiular

0

我认为在回收过程中您的视图没有被重新绘制。请检查您是否为RecyclerView设置了“setHasFixedSize=true”。如果是,请将其删除或将其设置为false。如果仍然无法解决问题,请尝试将TextView的宽度更改为wrap_content而不是0dp。


setHasFixedSize 没有起到作用。当存在太多内容时,wrap_content 会使其不遵守 app:layout_constraintWidth_percent,即扩展以占据整个屏幕的宽度。 - M-Wajeeh

0

我曾经遇到过同样的问题,我通过使用RelativeLayout并在TextView内设置属性android:maxWidth来解决它。

<?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">

       <TextView
            android:id="@+id/textViewChat"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autoLink="all"
            android:gravity="start"
            android:linksClickable="true"
            android:maxWidth="256dp"
            android:padding="8dp"
            android:textColor="@color/black"
            android:textSize="14sp" />
</RelativeLayout>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接