【发布时间】:2015-07-04 09:40:05
【问题描述】:
我有一个 ViewPager,其中一个页面有一个 FloatingActionButton。工具栏使用带有scroll|enterAlways 的 CoordinatorLayout,因此它会随着用户滚动而消失。
这会导致 FloatingActionButton 最初是不可见的,并随着用户滚动而滚动到视图中并且工具栏消失。
目的是让 FAB 始终固定在屏幕上。一个奇怪的想法是将它移动到包含 ViewPager 的布局中,但我只希望它在一页上。
这是顶层布局:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/new_toolbar"
app:layout_scrollFlags="scroll|enterAlways"
app:layout_collapseMode="pin"/>
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:background="@color/primary"
app:layout_scrollFlags="scroll|enterAlways"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp_main"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.CoordinatorLayout>
非常简单 - 一个滚动到视线之外的工具栏(向上滚动时立即返回),以及一个视图寻呼机。
ViewPager 页面的相关布局如下:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:src="@drawable/ic_add_black_48dp"
app:fabSize="normal"
android:id="@+id/add" />
</FrameLayout>
我尝试了一些随机的愚蠢行为,例如 app:layout_scrollFlags="" 和 app:layout_behavior="android.support.design.widget.FloatingActionButton.Behavior",但这些都没有帮助 - 我猜问题是 FrameLayout 的大小在没有工具栏的情况下覆盖了整个屏幕。解决这个问题的最佳方法是什么?
【问题讨论】:
-
将 FAB 放在视图寻呼机之外。通过回调或依赖注入在视图寻呼机片段中请求它。根据当前片段显示/隐藏它或更改其外观。
-
@EugenPechanec 绝对是一个可行的选择。我希望有别的东西,因为我不希望 FAB 的逻辑传播到页面之外,但除非有人有更聪明的想法,否则我将不得不这样做。
-
我知道你的痛苦,也有同样的问题。如果你看一下规格,FAB 总是停留在一个地方,并根据不断变化的片段改变背景和图像。但这不是在 Google 地图中发生的(有多个 FAB),所以这实际上取决于个人需求。
-
@EugenPechanec Bah,我想这就是要走的路,我最终以这种方式实现了它。随意写一个正确的答案,这样我就可以给你 25 分!