首页 > 解决方案 > Android wrap_content 无法在 recyclerview 上运行

问题描述

我有一个非常简单的 RecyclerView 从 Firestore 数据库加载数据。获取数据的代码没有问题,但是当我将视图持有者设置为 wrap_content 时,RecyclerView 不显示任何内容。但是,当我将其设置为 match_parent 时,它会加载数据。我试过使用

firestoreRecycler.setHasFixedSize(true)

但它没有做任何事情,当我使用 wrap_content 并使用 match_parent 时,数据根本没有显示,所以我必须滚动很多才能看到单个项目。

这是 RecyclerView 行布局的代码

<?xml version="1.0" encoding="utf-8"?>
    <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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp">

    <TextView
        android:id="@+id/listOfficeName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/listOfficeAddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/listOfficeName" />

</androidx.constraintlayout.widget.ConstraintLayout>

其余的没有什么相关的,只有 RecyclerView 的功能是我从 wrap_content 实际工作的教程中获得的。

提前致谢!

标签: androidgoogle-cloud-firestore

解决方案


ConstraintLayout中作为视图使用的recyclerview的距离被禁用,因为它不符合ConstraintLayout的逻辑。所以编辑recyclerview的height值如下:

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

高度 = 0dp


推荐阅读