我希望只要向下滚动就可以让fab隐藏起来,只要向上滚动就会显示我怎么能这样做,现在我正在尝试这个但是只有当它到达顶部并且在到达底部时隐藏它才会出现:
@Override
public boolean onStartNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton 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 FloatingActionButton 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 (CoordinatorLayout.SCROLL_INDICATOR_START == 16 && dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
child.hide();
} else if (CoordinatorLayout.SCROLL_INDICATOR_START == 16 && dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
child.show();
}
}
答案 0 :(得分:2)
如果您的布局中有recyclerView,则此代码可以帮助您:
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
if (dy > 0) {
fab?.hide()
} else if (dy < 0) {
fab?.show()
}
}
})
答案 1 :(得分:0)
请这样做,希望对您有所帮助。
@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();
}
}
}