Attribute “android:layout_width“ was already specified for element “androidx.recyclerview.widget.Rec

Android运行时报错,报错提示:Attribute "android:layout_width" was already specified for element "androidx.recyclerview.widget.RecyclerView".

解决:

这个错误表示android:layout_width属性在androidx.recyclerview.widget.RecyclerView元素中被指定了两次。为了解决这个问题,您需要找到对应的布局文件,并确保androidx.recyclerview.widget.RecyclerView元素的android:layout_width属性只被设置一次。

例如,以下布局文件将引发此错误:

<androidx.recyclerview.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_width="match_parent" />

请注意,android:layout_width属性被重复指定。要解决此问题,请从布局文件中删除重复的属性:

<androidx.recyclerview.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

现在,android:layout_width属性只被设置一次。保存更改并重新运行您的项目,该问题应该已解决。

But!!!此时我的RecycleView代码没有以上错误,那么就要看我的布局写的是不是有问题,下面是我的布局:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/subscribe_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</layout>

从上面提供的代码中,RecyclerView的声明是正确的。这里并没有出现android:layout_width重复的问题。

不过,问题出在您的<layout>标签上。<layout>标签只应该包含XML命名空间定义,而不应该包含android:layout_widthandroid:layout_height属性。为了解决这个问题,请将这些属性移动到<layout>标签内部的根布局中。例如:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/subscribe_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

在这个例子中,我将android:layout_widthandroid:layout_height属性从<layout>标签移除,并将RecyclerView放在了一个ConstraintLayout内。您也可以根据需要使用其他布局类型。现在,保存并重新运行您的项目,问题应该已经解决

猜你喜欢

转载自blog.csdn.net/Waterme10n/article/details/130352645