Best place to addHeaderView in ListFragment

2019-01-13 15:15发布

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?

7条回答
▲ chillily
2楼-- · 2019-01-13 15:46

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.

查看更多
登录 后发表回答