Android,layoutParams是否指向父视图,而不是视图本身



我在尝试动态更新视图的layoutParams时遇到了一个问题。

要更新的视图是ConstraintLayout,我想动态更改它的app:layout_constraintDimensionRatio属性。

片段XML:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LevelFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/board"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="32dp"
android:layout_marginBottom="32dp"
android:background="@color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>

但当我试图将其从Kotlin碎片代码中更改时

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
board = view.findViewById(R.id.board)
// Set ratio
val layoutParams = board!!.layoutParams as ConstraintLayout.LayoutParams
layoutParams.dimensionRatio = "5:1"
board!!.layoutParams = layoutParams
}

它在调试后失败,并出现以下错误:

android.widget.FrameLayout$LayoutParams不能强制转换为androidx.constraintlayout.widget.constraintlayout$LayoutParams

所以,我想知道为什么它抱怨FrameLayout到ConstraintLayout强制转换,因为layoutParams取自board视图,这是一个ConstraintLayout。。。

paramsLayout是指父视图,而不是视图本身吗?

如果是,如何更新视图dimensionRatio属性?

谢谢!

LayoutParams是父ViewGroup用于布局其子级的参数。每个子级都有自己的LayoutParams,它根据其父级的类型有一个特定的类型。即FrameLayout的子代以FrameLayout.LayoutParams作为LayoutParamsLinearLayout的子代将LinearLayout.LayoutParams作为LayoutParams等等。此外,它们不能相互转换,这意味着不能将LinearLayout.LayoutParams转换为FrameLayout.LayoutParams,因为它们有不同的LayoutParams实现方式。但所有的LayoutParams都附加了ViewGroup.LayoutParams,所以将它们转换为ViewGroup.LayoutParams是安全的
在您的情况下,您将board.layoutParams强制转换为ConstraintLayout.LayoutParams,但由于board的父级是FrameLayout,因此其LayoutParams的类型为FrameLayout.LayoutParams,无法强制转换为ConstraintLayout.LayoutParams
如果要解决此问题,必须将board的父级(即FrameLayout)替换为ConstraintLayout
如果您想了解LayoutParams的工作原理,也可以阅读此处。

最新更新