Best place to addHeaderView in ListFragment

前端 未结 7 1525
梦谈多话
梦谈多话 2020-12-05 02:37

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 t

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 02:56

    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 your ListFragment.onCreate(). Make sure you have a field variable that can hold the header view, maybe like:

    View mheaderView;
    

    Then in your ListFragment.onCreateView(), inflate the header View and assign it to your variable like so:

    View list_root = inflater.inflate(R.layout.fragment_list, null);
    // Get the list header - to be added later in the lifecycle
    // during onActivityCreated()
    mheaderView = inflater.inflate(R.layout.list_header, null);
    return list_root;
    

    Finally, in your ListFragment.onActivityCreated() you can now call ListFragment.getListView().addHeaderView(). Basically something like so:

    super.onActivityCreated(savedInstanceState);
    if (mheaderView != null)  this.getListView().addHeaderView(headerView);
    // Don't forget to now call setListAdapter()
    this.setListAdapter(listAdapter);
    

提交回复
热议问题