首页 > 解决方案 > 是否可以在不使用滚动视图(ScrollView、NestedScrollVIew...)的情况下使布局可滚动?

问题描述

你好,贝娄是我的布局:

  <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RelativeLayout
                android:id="@+id/layout_1"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:background="@color/color_dark_red">

            </RelativeLayout>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="640dp"
                android:background="@color/color_black"
                android:layout_below="@+id/layout_1" />
            
            <RelativeLayout
                android:id="@+id/layout_2"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_below="@+id/recycler_view"
                android:background="#0f0">

            </RelativeLayout>
            
        </RelativeLayout>

截图下方:

在此处输入图像描述

我想隐藏layout_1当用户向下滚动 recyclerView 或隐藏layout_2当用户向上滚动 recyclerView 时。

根据文档: 永远不要将 RecyclerView 或 ListView 添加到滚动视图。这样做会导致糟糕的用户界面性能和糟糕的用户体验。

我也不想使用,NestedScrollView因为它会在更新 recyclerView 时禁用(或删除) DiffUtil 工作,background Thread如下面的问题所述:

使用 DiffUtil,如何在更新 NestedScrollView 中包含的 recyclerView 时防止阻塞主线程?

在不使用 ScrollView 或 NestedScrollView的情况下,如何使recycler_view隐藏的layout_1向下滚动和向上滚动隐藏?layout_2

谢谢。

标签: androidandroid-layoutandroid-recyclerviewandroid-scrollviewandroid-nestedscrollview

解决方案


在这种情况下,您可以使用 recyclerView 滚动侦听器

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    super.onScrollStateChanged(recyclerView, newState);

    if (!recyclerView.canScrollVertically(1)) {
        // show the last item 
    }
 }
});

推荐阅读