Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Snackbar be shown from a fragment in the correct view?

In my fragment, I perform:

mActionHelper.showUndoBar(getView(), itemsList, lastPositionSelected);

The showUndoBar() method simply creates a Snackbar with the form:

Snackbar.make(view, message, Snackbar.LENGTH_LONG);

However, somehow the view is incorrect, as the Snackbar does not respond to swipe-to-dismiss gestures and only fills up the bottom-left quadrant in tablet split-view. Most of the Snackbar examples demonstrate calling the Snackbar from an Activity, so I think the fact that I am using a Fragment is the problem. How can I obtain and pass the correct View for the Snackbar to display correctly?

like image 327
Taylor Kline Avatar asked Jul 20 '15 14:07

Taylor Kline


People also ask

How do I use snackbar?

Snackbar in android is a new widget introduced with the Material Design library as a replacement of a Toast. Android Snackbar is light-weight widget and they are used to show messages in the bottom of the application with swiping enabled. Snackbar android widget may contain an optional action button.

Can a fragment have its own view?

Fragments cannot live on their own--they must be hosted by an activity or another fragment. The fragment's view hierarchy becomes part of, or attaches to, the host's view hierarchy.

How do you use fragments?

There are two ways to add a fragment to an activity: dynamically using Java and statically using XML. Before embedding a "support" fragment in an Activity make sure the Activity is changed to extend from FragmentActivity or AppCompatActivity which adds support for the fragment manager to all Android versions.


1 Answers

Your issue is not related to your use of Fragments.

If you don't have a CoordinatorLayout in your layout you will not have swipe to dismiss functionality enabled and on tablets the display of the Snackbar will be at the very bottom left of your layout. The Snackbar has a maximum width stopping it filling the complete width of a tablet, however you can also use the CoordinatorLayout to center the Snackbar on tablets if desired.

From the Android Snackbar.make documentation:

Snackbar will try and find a parent view to hold Snackbar's view from the value given to view. Snackbar will walk up the view tree trying to find a suitable parent, which is defined as a CoordinatorLayout or the window decor's content view, whichever comes first.

Having a CoordinatorLayout in your view hierarchy allows Snackbar to enable certain features, such as swipe-to-dismiss and automatically moving of widgets like FloatingActionButton.

like image 112
BrentM Avatar answered Sep 22 '22 07:09

BrentM