I'm thinking of a way to implement Android Snackbars in my app. Basically, I want to be able to show Snackbar from anywhere in the app.
As I found out, android.support.design.widget.Snackbar
performs the best when put in android.support.design.widget.CoordinatorLayout
. Otherwise, I cannot swipe it away, it shows over navigation drawer and doesn't interact with Floating Action Button.
So the question is: Is it a good practice to wrap ALL my layouts in CoordinatorLayout
, get the reference for it in a BaseActivity, so that it can be passed to Snackbar from almost anywhere?
That seems to be a solid way to ensure the Snackbar and other layout components behave correctly, but... well, means touching all layouts and having one BaseActivity which is extended by all other Activities and which would be accessed from any Fragment wanting to show a Snackbar.
Is there a better way?
These are the options you have. Use one of these as you need in the project.
The best way of doing this is what you already said in your question, add a BaseActivity
and extend all your activities from it. According to the official documentation of CoordinatorLayout
,
CoordinatorLayout
is intended for two primary use cases:
- As a top-level application decor or chrome layout
- As a container for a specific interaction with one or more child views
So CoordinatorLayout
is created primarily for this reason (Though there are also other reasons). There will be the least performance issues as mentioned in the documentation.
As already answered by Rainmaker, you can use a Activity with a reference to the CoordinatorLayout
layout in your layouts folder where the child will be a framelayout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="@+id/activity_root"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
Then you will be using only one activity with setContentView(R.layout.root_coordinate_layout)
. Then you will convert all other activities into fragments and add them with :
MyFragment myf = new MyFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction()
.add(R.id.your_layout, myf)
.commit();
This is another way of doing the same thing. But this is a bit more complex and need a lot of works to do.
In all your activity, instead of setContentView(R.id.your_layout)
, use this:
LayoutInflater inflater = LayoutInflater.from(this);
ConstraintLayout yourLayout = (ConstraintLayout) inflater.inflate(R.layout.your_layout, null, false);
CoordinatorLayout layout = new CoordinatorLayout(this);
// Set its property as you wish ...
layout.addView(mainScreen);
setContentView(layout);