Illya Bublyk
Illya Bublyk

Reputation: 722

SnackBar covers FAB

My layout is absolutely identical with this tutorial. But in this tutorial we use app:layout_behavior="pl.michalz.hideonscrollexample.ScrollingFABBehavior" in Fab XML, so SnackBar covers the Fab. Without this code Fab does not move followed by RecyclerView. How to show SnackBar correctly?

Snackbar.make(getActivity().findViewById(R.id.coordinatorLayout),
adapter.getNewsList().get(position).getTitle(), Snackbar.LENGTH_LONG).show();

Upvotes: 0

Views: 1373

Answers (2)

Anggrayudi H
Anggrayudi H

Reputation: 15155

Have you tried this?

...
View view = inflater.inlfate(R.layout.my_layout, parent, false);
...
Snackbar.make(view.findViewById(R.id.fab),
        adapter.getNewsList().get(position).getTitle(), Snackbar.LENGTH_LONG).show();
...
return view;

I assume that you call above code in Fragment, so I added view variable to call the findViewById() method.

Upvotes: 0

Lamorak
Lamorak

Reputation: 11137

The example you follow is pretty unlucky. The default behavior of FloatingActionButton within CoordinatorLayout is to move up when you display SnackBar. Since this code overrides the Behavior you lose this feature because the methods never call their super class implementations. Clearly the author have not thought about this. However, you can modify the ScrollingFABBehavior to extend the original Behavior and thus support SnackBar:

public class ScrollingFABBehavior extends FloatingActionButton.Behavior {
    private int toolbarHeight;

    public ScrollingFABBehavior(Context context, AttributeSet attrs) {
        super();
        this.toolbarHeight = Utils.getToolbarHeight(context);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
        return super.layoutDependsOn(parent, fab, dependency) || (dependency instanceof AppBarLayout);
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
        boolean returnValue = super.onDependentViewChanged(parent, fab, dependency);
        if (dependency instanceof AppBarLayout) {
            CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
            int fabBottomMargin = lp.bottomMargin;
            int distanceToScroll = fab.getHeight() + fabBottomMargin;
            float ratio = (float)dependency.getY()/(float)toolbarHeight;
            fab.setTranslationY(-distanceToScroll * ratio);
        }
        return returnValue;
    }
}    

This is actually the class from the example's github repository, I have found it just after I coded the same myself and wanted to test it. They only forgot to update the blog post :-/

Upvotes: 2

Related Questions