【问题标题】:android.widget.LinearLayout$LayoutParams cannot be cast to android.support.constraint.ConstraintLayout$LayoutParamsandroid.widget.LinearLayout$LayoutParams 不能转换为 android.support.constraint.ConstraintLayout$LayoutParams
【发布时间】:2019-10-09 20:41:13
【问题描述】:

我收到以下错误

java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams 无法转换为 android.support.constraint.ConstraintLayout$LayoutParams

【问题讨论】:

  • 请同时添加代码。

标签: android


【解决方案1】:

您的视图可能是 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 代码正确反映您的布局。

【讨论】:

    【解决方案2】:

    很明显,您不能将一种布局的 LayoutParams 转换为另一种布局。它与特定的布局类型相关联。因此,将您的布局从线性更改为约束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多