Search code examples
androidfindviewbyidsnackbar

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?


Solution

  • 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.