Aruka J Aruka J - 1 year ago 254
Android Question

Can findViewById( 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:


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?

Answer Source

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:

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( or some other call with findViewById( You could probably add the Lint check yourself however.

You can safely use findViewById( whenever you're inside an Activity.

You can safely use getView() inside a Fragment whenever onCreateView has been called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download