【问题标题】:RecyclerView is not trully wrap_content at the ScrollViewRecyclerView 在 ScrollView 上并不是真正的 wrap_content
【发布时间】:2025-12-03 12:45:01
【问题描述】:

我有一个ScrollView,,其中包含一个垂直的LinearLayout. 这是一个地方,我在其中添加了一些称为“部分”的视图。 “Section”是一个LinearLayout,,其中包含一个TextView 和`RecyclerView。

<ScrollView
    android:id="@+id/main_scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/sections_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />
</ScrollView>

部分:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textSize="@dimen/activity_starred_title_textsize" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

问题是RecyclerView 有时并不是真正的wrap_content。因此它会产生两种类型的问题(取决于我尝试使用的解决方案类型)。

  1. 它可以是不可滚动的(因此它与屏幕高度匹配,我无法向下滚动以查看里面的其余项目)。

  2. 可以嵌套滚动。

原来的问题是它有嵌套滚动。所以我希望RecyclerViews 与垂直LinearLayouts 一样简单,并且唯一必须具有滚动效果的是root ScrollView.

我尝试过做什么?

  1. 扩展GridLayoutManager 并覆盖canScrollVertically(). 方法:

    public boolean canScrollVertically(){ 返回假; }

  2. 扩展RecyclerView 类并覆盖

    @覆盖 公共布尔 onInterceptTouchEvent(MotionEvent 事件){ 返回假; }

    @覆盖 公共布尔 onTouchEvent(MotionEvent 事件){ 返回假; }

  3. 在任何可能的地方通过xml 禁用NestedScrolling

  4. 使用此解决方案覆盖 GridLayoutManagerSOLUTION

  5. 结合1-4

【问题讨论】:

  • 您是否尝试在布局中将 ScrollView 替换为 NestedScrollView?
  • @Buckstabue 没有。我现在试试。 Tnx
  • @Buckstabue 有帮助!不仅如此,无论如何都要感谢!
  • 类似的问题。 *.com/questions/39267532/…

标签: android android-layout android-recyclerview android-xml


【解决方案1】:

不要在ScrollView 中使用RecyclerViewListView。对于嵌套滚动,您应该使用NestedScrollView

NestedScrollViewScrollView 一样,但它支持充当 nested 在新旧版本上都滚动父和子 安卓的。默认启用嵌套滚动。

解决方案:

1.不要使用ScrollView,而是使用NestedScrollView作为Section部分的容器(RecyclerView和其他Views)。

<android.support.v4.widget.NestedScrollView
    android:id="@+id/main_scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/sections_layout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- Your Section:: RecyclerView and other Views -->

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

2. 对于滚动问题,请使用 setNestedScrollingEnabled(false) 到您的 RecyclerView

【讨论】:

    【解决方案2】:

    接下来是解决方案: 1.使用NestedScrollView 2.覆盖GridLayoutManager.canScrollVertically():

    public boolean canScrollVertically(){ return false; }
    

    【讨论】: