使用RecyclerView的CoordinatorLayout

7

我有一个LinearLayout,我希望当我在RecyclerView上向上滚动时隐藏它,并在向下滚动时重新出现;行为应该与Toolbar隐藏和重新出现的方式相同。

目前我已经做到了以下内容:

<android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

   <LinearLayout
        android:id="@+id/viewToHideOnScroll
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- other stuff inside the LinearLayout -->

   </LinearLayout>

   <RecyclerView
        android:id="@+id/recyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</android.support.design.widget.CoordinatorLayout>

据我目前了解,我可以在viewToHideOnScroll上指定app:layout_behavior值,这样它就可以根据recyclerView的滚动事件平稳地滚入和滚出视图。为此,我必须编写一个自定义类ViewToHideOnScrollBehavior并重写layoutDependsOn和一些其他方法(onNestedScroll?)。
如果这是正确的,这是我现在拥有的内容:
public class ViewToHideOnScrollBehavior extends CoordinatorLayout.Behavior<LinearLayout> {

public ViewToHideOnScrollBehavior(Context context, AttributeSet attrs) {}

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, LinearLayout child, View dependency) {
        return dependency instanceof RecyclerView;
    }

    // some other method to override, I don't know
}

能否给我一些提示,还是我做错了什么?

我一直在按照 https://lab.getbase.com/introduction-to-coordinator-layout-on-android/ 的介绍操作。

1个回答

19

当用户滚动您的线性布局时,您必须将 LinearLayout 放在 AppBar 布局中。您需要像下面这样创建一个 XML 文件。

 <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

     <LinearLayout
                android:id="@+id/lytSearchBar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorPrimary"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:padding="@dimen/fivedp"
                app:layout_scrollFlags="scroll|enterAlways" // layout_scrollFlags for scroll layout
                android:visibility="visible">

     </LinearLayout>
     </android.support.design.widget.AppBarLayout>

      <android.support.v7.widget.RecyclerView
            android:id="@+id/rvOrderList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/lytSearchBar"
            android:paddingTop="@dimen/tendp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

在RecyclerView中不要忘记像上面的xml中所示添加属性app:layout_behavior


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接