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