findViewById() returns null when I call it in onCreate()

Activity findViewById() searches the activity’s view hierarchy set with setContentView() for the given view id. The view you appear to be looking for is in a fragment and not in the activity hierarchy (yet). Fragment transactions are not immediate either so even if you add it to the container in the activity hierarchy, it is not attached there right away but only when the transaction is processed.

In theory it’s possible to synchronously execute pending fragment transactions with executePendingTransactions(). However, it’s better to just move the code that touches a fragment’s views in its onCreateView(). Fragments and their hosting activities are supposed to be relatively independent of each other, so an activity accessing a fragment’s internals should be avoided.

Leave a Comment