向 FloatingActionButton 添加多个行为

Adding more than one behavior to a FloatingActionButton

在我上一个项目中,我发现了 Android Material 设计库。它非常强大,我用它玩得很开心。我向我的 FloatingActionButton 添加了自定义行为,因此它会在向下滚动时消失。现在我提到,如果显示 SnackBar,FAB 的位置将不再自动处理。

经过一些调试后我发现,将锚点设置为 recyclerView 并添加自定义行为以根据 SnackBar 从 CoordinatorLayout 滚动默认行为已经消失。

所以我问自己,我可以向我的 FAB 添加不止一种行为吗?或者我能以某种方式告诉它,默认的不应该被覆盖,而是应该被扩展吗?

或者我可以写多个吗?

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

好的,我找到了实现所需行为的方法,但它更多的是解决方法而不是答案。

如果我在 Java 代码中以编程方式添加 Scrollbehavior,如下所示:

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState ==  RecyclerView.SCROLL_STATE_IDLE) {
                sendMailFAB.show();
            }
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (dy > 0 && sendMailFAB.isShown())
                sendMailFAB.hide();
        }
    });

然后删除自定义行为,它在 .xml 文件中的锚点,CoordinatorLayout 的默认行为处理 Snackbar 和 onScrollListener 的滚动行为。

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout   
    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:id="@+id/fragment_coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="de.flowment.designExample.StartActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/startRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">

    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:layout_anchorGravity="bottom|end"
        android:src="@android:drawable/ic_dialog_email" />

    <!-- DELETE THIS PART, BECAUSE IT'S NOT USED ANYMORE AND BLOCKS THE DEFAULT.
    app:layout_anchor="@id/startRecyclerView"
    app:layout_behavior="de.flowment.designExample.FABScrollBehavior" />-->


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

所以我实现了两种行为,但正如我所说,这更像是一种解决方法。