RecyclerView不滚动并显示所有项目

pst*_*cki 37 android android-recyclerview

我在ScrollView中有一个RecyclerView(和一些其他视图).目前,RecyclerView的布局非常小(它显示了它包含的5个中的2个项目)并且它独立于ScrollView滚动,这显然不是很好的用户体验.我想让RecyclerView不滚动和扩展,以便所有项目都可见.

(我知道在这种情况下使用RecyclerView是愚蠢的.我只是这样做,因为应用程序中的其他地方我需要一个普通的RecyclerView滚动等但是同样的内容,我不想重复代码).

nat*_*rio 57

这很简单,只需将RecyclerView高度设置为wrap_content.

您还可以从回收器视图上禁用嵌套滚动中受益,如下所示:

RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setNestedScrollingEnabled(false);
Run Code Online (Sandbox Code Playgroud)

  • 您忘了提到必须使用NestedScrollView而不是ScrollView.我在下面写过这篇文章. (19认同)
  • @William是的,这就是RecyclerView上wrap_content的意义所在。它将绑定所有项目。我个人认为这是一个错误-RecyclerView应该在项目不在屏幕上时回收,而不仅是在项目超出边界时。但是我提交的错误被忽略了。因此,现在您应该只将wrap_content用于小型数据集,或者使用按钮加载更多项目。 (2认同)

and*_*per 25

setNestedScrollingEnabled(false)的解决方案并不像它应该的那样完整:你需要对NestedScrollView的子节点使用NestedScrollView而不是ScrollViewfocusableInTouchMode ="true".

如果你坚持使用ScrollView,你还应该将minHeight设置为RecyclerView,并设置overScrollMode ="never".在这种情况下,它仍然不是一个好的解决方案,因为在某些情况下minHeight可能还不够

您应该考虑的其他替代解决方案:

  1. 使用单个RecyclerView替换ScrollView和RecyclerView,它具有ScrollView中具有其他视图类型的视图

  2. 请改用GridLayout或其他布局.


Val*_*ova 12

乍一看,也许还不太清楚如何处理所有这些答案。我只是试过了,工作的是:

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/person_properties"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
...
        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:overScrollMode="never" />
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>
Run Code Online (Sandbox Code Playgroud)

无需以编程方式更改任何内容。


Ami*_*ngh 10

在您的 activity.xml 文件中

<androidx.core.widget.NestedScrollView 
    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"
    tools:context=".ActivityName">

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

     </androidx.recyclerview.widget.RecyclerView>

</androidx.core.widget.NestedScrollView>
Run Code Online (Sandbox Code Playgroud)

在 RecyclerView 中使用android:nestedSrollingEnabled="false"并使用NestedScrollView作为父滚动视图。


小智 8

如果您在 ScrollView 中使用 RecyclerView 然后替换ScrollViewNestedScrollView并启用嵌套滚动

android:nestedScrollingEnabled="false"
Run Code Online (Sandbox Code Playgroud)

这解决了我的问题