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?
As short solution that worked for me:
My solution:
I had some problems with header layout height, so I followed this solution:
Header is a instance of View and DiarioAdapter is a custom ArrayAdapter.
UPDATE 1
If you have problems with duplicate listfragment, just change FragmentTransaction ADD for REPLACE.
This is my solution for handling footer/header in list view. I use it in retained fragment. Adapter is initialized in renderView() method. This method can be called how many times you need (e.g. for refresh data in view) and footer/header works fine. I tested this code on Android 2,3,4.
I don't know if you have solved your problem but here is a solution that worked for me:
Do not call
ListFragment.setListAdapter()
in yourListFragment.onCreate()
. Make sure you have a field variable that can hold the header view, maybe like:Then in your
ListFragment.onCreateView()
, inflate the header View and assign it to your variable like so:Finally, in your
ListFragment.onActivityCreated()
you can now callListFragment.getListView().addHeaderView()
. Basically something like so:This solution works with screen flipping:
In onActivityCreated():
And in onDestroyView()