I want to be able to display Snackbars but I am confused by this notion that I have to supply it with a View. You'd think it'd allow you to display the Snackbar at the bottom of the screen by default, but maybe I am missing something.
Anyway supposedly this can be done by using the view:
findViewById(android.R.id.content)
However I get a warning that this may be null even though it always seems to work wherever I try it. When can it possibly be null?
findViewById
can always be null, if you try to find a view that doesn't exist in the current layout.
The warning is just a help. It's probably very generic and if you look inside the source of the Activity class, you will find this method:
@Nullable
public View findViewById(@IdRes int id) {
return getWindow().findViewById(id);
}
The Nullable
annotation just informs the compiler that there might be a possibility of getting a null
reference here and Lint will react to this. It doesn't know how to differentiate between a findViewById(android.R.id.content)
or some other call with findViewById(R.id.myCustomLayoutId)
. You could probably add the Lint check yourself however.
You can safely use findViewById(android.R.id.content)
whenever you're inside an Activity
.
You can safely use getView()
inside a Fragment
whenever onCreateView
has been called.
Pass the activity if your not in AppCompatActivity
public static void snackBar(Activity activity, String MESSAGE) {
Snackbar.make(activity.findViewById(android.R.id.content), MESSAGE, Snackbar.LENGTH_LONG).show();
}
If you have a context you can try like this
public static void snackBar(Context context, String MESSAGE) {
Snackbar.make(((Activity)context).findViewById(android.R.id.content), MESSAGE, Snackbar.LENGTH_LONG).show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With