Although Pragnani's answer is close, there's little educational value in it. Besides, there's a more appropriate option to his 2nd statement.
Where should I put this code in the fragment? In the onCreate()?
onCreateView()? onActivityCreated()? and why?
The short answer is: either onCreateView()
or onActivityCreated()
will do. The view hierarchy won't be created until onCreateView()
, so that's the earliest point in the fragment's life cycle that you could inflate the views and attach click listeners etc. Since onActivityCreated()
will always be run after onCreateView()
, that's a suitable location too. onCreate()
may be skipped in favour of the system temporarily detaching the fragment and reattaching it, e.g. when retaining fragments.
Pragnani is correct by pointing out that inflating the views of a fragment is slightly different from inflating views in an activity. More specifically: a fragment does not define a findViewById()
method, so you'll need to call it on some other object.
Rather than using getActivity().findViewById()
, you'll want getView().findViewById()
. The reason for this is that if you use the activity for the view lookups, then you'll get into trouble when multiple fragments with the same view IDs are attached to it. This will be the case if you reuse view ids in the layouts of your various fragments, or if you show two identical fragments that display different data. In both cases, only the first match would ever be returned, whereas you really want to the view to be looked up in the conext of the fragment. That's exactly what getView()
returns, the fragment's root view (that you returned in onCreateView()
), and thus limits the scope of the lookup appropriately.