CardView 中不允许元素 LinearLayout

Element LinearLayout is not allowed in CardView

注意:请先阅读问题,然后再将其标记为重复!我已经提到了类似的问题并没有解决我的问题。


我正在使用 android.support.v7.widget.CardView 作为布局 xml。但是,当我在 CardView 中放置 LinearLayout 时,Android Studio 会出现以下错误“ 此处不允许使用元素 LinearLayout".

事实上任何类型的小部件(如TextView)都会导致这个错误,我已经尝试了LinearLayout flagged if used in CardView link的解决方案,这是重新启动Android工作室。但它没有用。下面是我的 xml 代码:

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

而且我也会post截图!

可能是什么问题??

所以,建议的集合,只是为了确定:

  • 重启AS
  • 正在使缓存失效并重新启动
  • 检查是否添加了正确的依赖
  • 清理并重建项目
  • 在另一个 file/project
  • 中尝试相同的代码
  • 正在尝试查找项目的备份
  • 可能电脑重启了

确保您没有在卡片视图中输入约束(魔术棒),因为它会向卡片视图添加约束并阻止任何线性布局。

检查是否为 CardView 正确添加了 Gradle 依赖项。

在build.gradle

implementation 'com.android.support:cardview-v7:28.0.0'

然后在XML

<androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="#fff"
        app:cardCornerRadius="2dp"
        android:elevation="2dp">

    <TextView android:layout_width="match_parent"
           android:layout_height="wrap_content" android:id="@+id/textView" />

</androidx.cardview.widget.CardView>

只需将 android.support.v7.widget.CardView 替换为 androidx.cardview.widget.CardView