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:
View footerView = View.inflate
(getActivity(), R.layout.list_footer_loader_view, null);
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:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
I like to do it in the onCreate
because it's not relevant for the activity. Now with the setRetainInstance(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:
getListView().addFooterView(footerView);
And then connect the adapter to the list:
setListAdapter(adapter);
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):
MyFragment myFragment = (MyFragment)
getFragmentManager().findFragmentByTag(tag);
if (myFragment == null) {
myFragment = MyFragment.newInstance();
getFragmentManager().beginTransaction().
add(myFragment, tag).commit();
}
This will only create the fragment once, if the tag is unique for that fragment of course.