1

I wanted to add a header to one of my ListViews in my application and since I haven't done this before I googled for that.
Now my first approach was to just add to the XML file a TextView before the ListView just like this:

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#98cfc8"
    android:gravity="center_horizontal"
    android:text="HARD" />

And it works, I have a header on top of my ListView now but in a tutorial I read about the headers was written that I should inflate it after I create it in the XML with such code:

LayoutInflater inflater = getLayoutInflater();
    ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView,
            false);
    ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
            false);
    listView.addHeaderView(header, null, false);
    listView.addFooterView(footer, null, false);

What is inflation and what does it change compared to my current approach ?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Mik
  • 37
  • 1
  • 5
  • I prefer the first method, because the header (and the footer as well) stays fixed to the position and doesn't scroll with the items. As it should. While, with the second method, the "header" and the "footer" scroll away with the other items. And this (as I see it) should not happen. – Phantômaxx Mar 05 '17 at 18:34

3 Answers3

2

And it works, I have a header on top of my ListView now

Actually, that's not a header. It's simply a View above the list.

listView.addHeaderView is the correct way to put a header as part of the listview.

Inflating is the process of turning an XML file into a View object

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

The thing is that you have to inflate (render) view to "allow" android show your staff on the screen

Sometimes when there is a onCreate() method used there is no need to do this because it has already been done by the system itself

Trew laz
  • 29
  • 4
0

In your approach, the the header you've created will not scroll. It will always be displayed above the list.

With addHeaderView(), it will be part of the list so it can scroll on and off the screen along with the rest of your list items.

Eurig Jones
  • 8,226
  • 7
  • 52
  • 74