实现滚动感知 FloatingActionButton 的推荐方法
Recommended way of implementing a scroll-aware FloatingActionButton
我正在按照 Material 设计构建一个应用程序,我想知道如何在滚动时隐藏 FAB。谷歌搜索导致了几个答案,有人说提供自定义 onScrollListeners 等,有人说实现布局行为。有 standard/recommended 的方法吗?一种方法比另一种方法有什么优势?
最好的方法是使用支持设计库中提供的FloatingActionButton
,并重新定义其行为。例如,看看 this class.
您只需将其复制粘贴到您的项目中,然后将此行为分配给您的 FloatingActionButton
:
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="@dimen/fab_margin"
app:layout_behavior="com.your.package.name.ScrollAwareFABBehavior" />
完成后,您的 FAB 将自动对滚动手势做出反应 hide/show。当然,与所有 Behavior
一样,只有当您使用 CoordinatorLayout
作为根视图时才有效。
好处:
- 使用官方库;
- 使用
Behavior
s 这绝对是监听滚动事件最简单的方法。由于 FloatingActionButton
是设计库的一部分(它实现了 Behavior
s),我想说这几乎是 官方 方式;
- 那个行为 class 是 Ian Lake 写的,据我所知他在 google 工作。
我正在按照 Material 设计构建一个应用程序,我想知道如何在滚动时隐藏 FAB。谷歌搜索导致了几个答案,有人说提供自定义 onScrollListeners 等,有人说实现布局行为。有 standard/recommended 的方法吗?一种方法比另一种方法有什么优势?
最好的方法是使用支持设计库中提供的FloatingActionButton
,并重新定义其行为。例如,看看 this class.
您只需将其复制粘贴到您的项目中,然后将此行为分配给您的 FloatingActionButton
:
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="@dimen/fab_margin"
app:layout_behavior="com.your.package.name.ScrollAwareFABBehavior" />
完成后,您的 FAB 将自动对滚动手势做出反应 hide/show。当然,与所有 Behavior
一样,只有当您使用 CoordinatorLayout
作为根视图时才有效。
好处:
- 使用官方库;
- 使用
Behavior
s 这绝对是监听滚动事件最简单的方法。由于FloatingActionButton
是设计库的一部分(它实现了Behavior
s),我想说这几乎是 官方 方式; - 那个行为 class 是 Ian Lake 写的,据我所知他在 google 工作。