Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple constraint layout child with max width in RecyclerView

I am trying to create a TextView such that it wraps its content until it reaches its max width. Following code kind of achieves that perfectly until it is used in RecyclerView. It seems like TextView doesn't measure its width again after I change its text in onBindViewHolder().

<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




However notice how it works fine if I invoke requestLayout() on TextView in onBindViewHolder() below:

Update: Following code in onBindViewHolder() works too.

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

parent being ConstraintLayout.

enter image description here

Does anyone understand whats going on here? Is this a bug in ConstraintLayout? Invoking requestLayout() in onBindViewHolder() is a bad practice and I don't want to do that.

like image 325
M-WaJeEh Avatar asked Jan 22 '26 18:01

M-WaJeEh


1 Answers

I know its month late, but I recently encountered this problem, and couldn't find an answer either. The changing ConstraintSet() posed by the author works, but always has the question in mind if this is efficient. Another solution is to change app:layout_constraintWidth_max="wrap" to app:layout_constraintWidth_default="wrap" That worked for me, the recyclerView updates the constraint correctly when recycling the view holders

like image 97
Yakun Li Avatar answered Jan 24 '26 11:01

Yakun Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!