Search code examples
javaandroidlistviewandroid-fragmentsandroid-listfragment

Add a custom layout before the list displayed by the adapter of a ListFragment


I have a ListFragment that displays a list. All good. I wanted to put some well formatted textview preceding the list.
I tried creating a linear layout with a textview and adding it as a header to the list but it does not work.
The following does work:

TextView tv = new TextView(getActivity());
 tv.setText(“Some title with comments”);
 getListView().addHeaderView(tv);
 tv.setGravity(Gravity.LEFT);
 tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);

I get the text before the list but I would like to actually set a layout instead as I would like text with 2 different fonts (it is like a title/caption with big font and a small description with smaller font).
How can I do that?
I don’t have any layout with list view defined. I only have a ListFragment and my custom listAdapter

Update:
What I also tried and did not work:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.headerView = inflater.inflate(R.layout.my_list_header, container, false);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

And later when setting the adapter:
getListView().addHeaderView(this.headerView);
But I got exceptions


Solution

  • Here are the steps for properly adding a header in a ListFragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          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.my_list_header, null);
          return list_root;
    
        }
    
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
         super.onActivityCreated(savedInstanceState);
         if (mheaderView != null)  this.getListView().addHeaderView(headerView);
         // Don't forget to now call setListAdapter()
         this.setListAdapter(listAdapter);
    }
    
    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
    
        // free adapter
        setListAdapter(null);
    }