I'm having some trouble setting up my custom header in my list.
I'm creating a ListFragment with a custom adapter. I have the list working fine, but I'm trying to figure out where in the lifecycle of a Fragment to attach the header.
I know the header has to be added before you set your adapter.
I tried adding my header in onActivityCreated, but that gets called every time my Fragment comes back from the backstack, and since I also set my adapter in onActivityCreated, it fails.
I tried adding it in onCreate, but the view hierarchy isn't available at that stage of the lifecycle.
I tried adding it in onCreateView, but I couldn't cast the view returned from inflate to a ListView. So I couldn't add my header to a vanilla View.
Any thoughts?
I am currently using the following solution in my class extending
ListFragment
:1) You, in your class
onActivityCreated
check if your adapter (which is a class variable) is null, then instantiate it. Then, inflate the footer, for example like this:You do only have to do this once! The footerView and the adapter only has to be created once. I create both of these in my
onActivityCreated
Now to the "hard part", set your fragment in your onCreate to like this:
I like to do it in the
onCreate
because it's not relevant for the activity. Now with thesetRetainInstance(true)
your fragment will not be recreated after the activity is destroyed, an event such as a screen orientation.Now after those rows add the footer like this:
And then connect the adapter to the list:
This should be done every time the activity dies, do this in
onActivityCreated
.And one of the other important things you should generally think about when it's coming to fragments is that you don't create the fragment every time the activity's
onCreate
is called.For example do this (if your NOT using the supportpackage):
This will only create the fragment once, if the tag is unique for that fragment of course.