我有一个正在尝试完成的任务:当字体比例配置更改时,以编程方式更改约束并更新布局。这里我通过视图绑定在 recyclerview 元素上有以下代码。
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
以前,recyclerview 上的约束不是与父级对齐,而是与父级内的另一个 imageview 对齐。 Imageview距父级的开始和结束的边距约为75dp; recyclerview 位于 imageview 的正下方。 XML 如下:
<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" />
这是recyclerview绑定的apply块下的一行:width = LayoutParams.MATCH_CONSTRAINT,这是行不通的;视图呈现时就好像约束仍然是 imageview 的前一个边缘;只有当我使用 MATCH_PARENT 而不是 MATCH_CONSTRAINT 时,它才能正确约束,但为什么会这样呢?
我现在有了一个可行的解决方案,但这更多地是一个问题:为什么在 ConstraintLayout LayoutParams 元素上,match_constraint 与 match_parent 相比,以编程方式不起作用?
Imageview 与父级的开始和结束的边距约为 75dp 根据您的代码,您设置了 imageView:
android:id="@+id/imageview" android:layout_width="0dp" 应用程序:layout_constraintEnd_toEndOf =“父” 应用程序:layout_constraintStart_toStartOf =“父”
看起来这个 imageView 与父级的开始和结束的边距不是 75dp。这里应该是一个
android:layout_marginHorizontal =“75dp”
建立利润
在您的回收站视图中您有:
应用程序:layout_constraintEnd_toStartOf =“@id / imageview” 应用程序:layout_constraintStart_toEndOf =“@id / imageview”
设置EndToStart和StartToEnd有点奇怪 同时。尝试 StartToStart 和 EndToEnd 看看是否有效