I have a task that I'm attempting to accomplish: to change constraints and update the layout programmatically when font scale configuration changes. Here I have the following code on a recyclerview element via view binding.
binding?.recyclerview?.apply {
if(resources.configuration.fontScale >= 1.3f) {
val layoutParams = this.layoutParams as ConstraintLayout.LayoutParams
this.updateLayoutParams {
layoutParams.apply {
startToStart = LayoutParams.PARENT_ID
endToEnd = LayoutParams.PARENT_ID
width = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT // <=Problem statement here
setMargins(UserInterfaceUtil().convertDPToPixel(30), 0, UserInterfaceUtil().convertDPToPixel(30), 0)
}
}
}
//...adapter code not given as not necessary to the problem
}
//functions convertDPToPixel not given because self explanatory
Previously, the constraints on the recyclerview were aligned not to the parent, but to another imageview inside the parent. Imageview is about 75dp margined from the start and end of parent; recyclerview is right below the imageview. XML follows:
<ImageView
android:id="@+id/imageview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:adjustViewBounds="true"
android:contentDescription="image content description"
android:scaleType="fitCenter"
android:src="@drawable/src_image"
android:visibility="visible"
app:layout_constraintBottom_toTopOf="@id/recyclerview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/header_text" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:background="@color/grey"
android:textColor="@color/darkGrey"
android:textStyle="italic"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/imageview"
app:layout_constraintStart_toEndOf="@id/imageview"
app:layout_constraintTop_toBottomOf="@id/imageview" />
It is the line under the apply block for the recyclerview binding: width = LayoutParams.MATCH_CONSTRAINT, that isn't working; the view renders as if the constraint is still the previous edge of imageview; only when I use MATCH_PARENT instead of MATCH_CONSTRAINT, does it constrain properly, but why is that?
I have a working solution now, but this serves more as a question of why match_constraint programmatically didn't work vs match_parent on a ConstraintLayout LayoutParams element?
Imageview is about 75dp margined from the start and end of parent. According to your code, you set your imageView:
It seems that this imageView is not 75dp margined from the start and end of parent. Here should be a
to build that margin
In your recyclerView you have:
It's kind of weird to set EndToStart and StartToEnd at the same time. Try StartToStart and EndToEnd to see if it works