Reputation: 17284
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>
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
.
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.
Upvotes: 3
Views: 1132
Reputation: 11
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
Upvotes: 1
Reputation: 41
I think your view is not getting redrawn during the recycling process. Check if you have 'setHasFixedSize=true' set for the recyclerview. Remove it or make it false. If it still does not work try changing the TextView width to wrap_content instead of 0dp.
Upvotes: 0
Reputation: 3261
I have faced the same issue and i solve it by using RelativeLayout
and set property android:maxWidth
inside the TextView
.
<?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>
Upvotes: 0