首页 > 解决方案 > 宽度和高度为 match_parent 的 Recyclerview 返回固定大小错误

问题描述

生成 APK/Signed Bundle 时,lintVitalRelease 返回此报告:

<issue
    id="InvalidSetHasFixedSize"
    severity="Fatal"
    message="When using `setHasFixedSize() in an `RecyclerView`, `wrap_content` cannot be used as \&#xA;a value for `size` in the scrolling direction."
    category="Correctness"
    priority="5"
    summary="When using `setHasFixedSize() in an `RecyclerView`, `wrap_content` cannot be used as \&#xA;a value for `size` in the scrolling direction."
    explanation="When a RecyclerView uses `setHasFixedSize(...)` you cannot use `wrap_content` for  size in the scrolling direction."
    errorLine1="        recyclerView.setHasFixedSize(true);"
    errorLine2="        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
    <location
        file="/home/Documents/MyProject/app/src/main/java/com/myproject/MainActivity.java"
        line="97"
        column="9"/>
</issue>

这显然不是真的,因为我的布局文件如下所示:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parent_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/refresh_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:clipToPadding="false"
        android:overScrollMode="never"
        android:paddingTop="8dp"
        android:scrollbars="none"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

lint 是错误的还是我搞砸了?

在我将 kotlin 与我的 java 项目集成后,这成为了一个问题!

标签: javaandroidandroid-layoutandroid-recyclerview

解决方案


您在代码中的错误可能是这样的

<android.support.v7.widget.RecyclerView
    android:id="@+id/my_recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

在这种情况下,我们将使用 my_recycler_view.setHasFixedSize (true)

<android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

而在这另一个我的 recyclerview.setHasFixedSize (false) 中,如果我们也使用 wrap_content 作为宽度,这适用


推荐阅读