谷歌已经发布了设计库,我正在使用
compile 'com.android.support:design:22.2.1'
然而,我看不到任何关于如何使用这个库以及如何在滚动中动态显示FAB
条的代码示例。我想我可以监听ListView
上的滚动事件,然后自己制作按钮动画,但这不是已经包含在API中了吗(这难道不是这个支持库的意义所在吗)。
有这样的例子吗?
发布于 2016-01-14 20:28:54
如果你正在使用RecyclerView
,并且你正在寻找一些简单的东西,你可以尝试这个:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener(){
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy){
if (dy > 0)
fabAddNew.hide();
else if (dy < 0)
fabAddNew.show();
}
});
通过将0
替换为常量,您可以调整触发灵敏度,提供更流畅的体验
发布于 2015-08-17 03:22:39
使用自定义CoordinatorLayout.Behavior使组件对滚动事件做出反应是最容易的,因为当您覆盖onStartNestedScroll()时,它们会自动接收滚动事件。
隐藏和显示在此FABAwareScrollingViewBehavior中找到的FAB on scroll的示例行为,构建于cheesesquare之上
public class FABAwareScrollingViewBehavior
extends AppBarLayout.ScrollingViewBehavior {
public FABAwareScrollingViewBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent,
View child, View dependency) {
return super.layoutDependsOn(parent, child, dependency) ||
dependency instanceof FloatingActionButton;
}
@Override
public boolean onStartNestedScroll(
final CoordinatorLayout coordinatorLayout, final View child,
final View directTargetChild, final View target,
final int nestedScrollAxes) {
// Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
|| super.onStartNestedScroll(coordinatorLayout, child,
directTargetChild, target, nestedScrollAxes);
}
@Override
public void onNestedScroll(
final CoordinatorLayout coordinatorLayout, final View child,
final View target, final int dxConsumed, final int dyConsumed,
final int dxUnconsumed, final int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target,
dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
if (dyConsumed > 0) {
// User scrolled down -> hide the FAB
List<View> dependencies = coordinatorLayout.getDependencies(child);
for (View view : dependencies) {
if (view instanceof FloatingActionButton) {
((FloatingActionButton) view).hide();
}
}
} else if (dyConsumed < 0) {
// User scrolled up -> show the FAB
List<View> dependencies = coordinatorLayout.getDependencies(child);
for (View view : dependencies) {
if (view instanceof FloatingActionButton) {
((FloatingActionButton) view).show();
}
}
}
}
}
滚动视图将使用app:layout_behavior="com.support.android.designlibdemo.FABAwareScrollingViewBehavior"
而不是app:layout_behavior="@string/appbar_scrolling_view_behavior"
但是,如果您愿意,可以用任何操作替换hide()
和show()
。有关如何做到这一点的详细信息,可以在this post、follow up post for v22.2.1和follow up post for v25.1.0中找到。
请注意,这就像设计库的所有滚动行为一样,要求您的视图支持嵌套滚动,这目前将您限制为NestedScrollView、RecyclerView - ListView
和ScrollView
,它们只能在API21+设备上工作。
发布于 2015-12-18 21:42:38
使用CoordinatorLayout是最好的方法。但是,如果您想将listener附加到ListView或RecyclerView,您也可以这样做。我认为更具可定制性。这是我在git集线器上的例子。
Github Project: Hide FAB(material Library) with listview
https://stackoverflow.com/questions/32038332
复制相似问题