【发布时间】:2019-10-09 20:41:13
【问题描述】:
我收到以下错误
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams 无法转换为 android.support.constraint.ConstraintLayout$LayoutParams
【问题讨论】:
-
请同时添加代码。
标签: android
我收到以下错误
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams 无法转换为 android.support.constraint.ConstraintLayout$LayoutParams
【问题讨论】:
标签: android
您的视图可能是 LinearLayout 的子视图(而不是 ConstraintLayout 的子视图)。所以,你必须使用:
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams()
一些背景:如果你有这个布局,例如
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/child_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
如果您尝试从child_view 获取LayoutParams,您将获得LinearLayout.LayoutParams 的实例(因为child_view 是LinearLayout 的子级)。
另一方面:
<ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/child_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</ConstraintLayout>
这会给你ConstraintLayout.LayoutParams 对象。
因此,您必须确保您的 java 代码正确反映您的布局。
【讨论】:
很明显,您不能将一种布局的 LayoutParams 转换为另一种布局。它与特定的布局类型相关联。因此,将您的布局从线性更改为约束。
【讨论】: