Floating Action Button in an Activity - how to anchor to a recyclerview in a fragment?
Have you tried anchor it to the viewpager?
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
app:layout_anchor="@id/viewpager"
app:layout_anchorGravity="bottom|right|end"
</android.support.design.widget.CoordinatorLayout>
Then you extend a FloatingActionButton.Behavior
to repond to CoordinatorLayout events:
public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
super();
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
nestedScrollAxes);
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child,
View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,
dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
child.hide();
} else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
child.show();
}
}
}
And add this to your FloatingButton:
app:layout_behavior="com.package.yourapp.ScrollAwareFABBehavior"
It's well explained here:
https://guides.codepath.com/android/Floating-Action-Buttons
Complementing @petrusgome's answer:
The provided solution didn't work for me. I had an issue where the FAB would not show again after scrolling the recyclerview list down.
To fix it, I just had to replace child.hide()
with the following code:
child.hide(new FloatingActionButton.OnVisibilityChangedListener() {
@Override
public void onHidden(FloatingActionButton fab) {
super.onHidden(fab);
fab.setVisibility(View.INVISIBLE);
}
});
The full explanation can be found here: scrolling issue