android.widget.LinearLayout$LayoutParams 不能转换为 android.suppo



我收到以下错误

java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams 不能强制转换为 android.support.constraint.ConstraintLayout$LayoutParams

您的视图可能是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_viewLinearLayout的子实例(。

另一方面:

<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 强制转换为另一个布局。它与特定的布局类型相关联。因此,请将布局从线性更改为约束。

最新更新