Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can findViewById(android.R.id.content) ever return null for Snackbars?

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?

like image 881
AJJ Avatar asked Jan 06 '23 22:01

AJJ


2 Answers

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.

like image 190
Darwind Avatar answered Mar 04 '23 18:03

Darwind


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();
}
like image 30
Andan H M Avatar answered Mar 04 '23 19:03

Andan H M