首页 > 解决方案 > RecyclerView max_height 和 wrap_content

问题描述

我在约束布局中有一个回收器视图,它显示来自数据库的数据。我希望最大高度为 500dp,但问题是当它超过该尺寸时,它会从视图底部切割一部分。我不知道会是什么问题。

这是 RecyclerView 的 xml:

<?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="fill_parent"
    android:layout_height="wrap_content"
    android:maxHeight="500dp"
    tools:context=".histDialog">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:padding="3dp"
        app:layout_constrainedHeight="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

recyclerview 出现在一个对话框样式的活动中。

我已经尝试了我能想到的所有可能的事情,但我无法让它发挥作用。

标签: androidandroid-recyclerviewandroid-constraintlayout

解决方案


我找到了解决方案。这是现在的 XML:

<?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="wrap_content"
    android:layout_height="wrap_content"

    tools:context=".histDialog">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/colorPrimary"
        android:clipToPadding="true"
        android:padding="3dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintHeight_max="500dp"
        app:layout_constraintHeight_min="50dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

重要的部分是:

        android:layout_height="0dp"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintHeight_max="500dp"
        app:layout_constraintHeight_min="50dp"

对于 RecyclerView。我花了足够长的时间才意识到这很简单。希望这也可以帮助其他人。


推荐阅读