ListView with Title

Matt picture Matt · Aug 21, 2013 · Viewed 22.7k times · Source

Is there a way to insert another View above the List in a ListView? For example, I want a Title Bar (TextView) that sits on top of the List, and scrolls out of view as the List scrolls. I can think of two ways so far of doing this, but both are hacks.


Idea #1 - Use a LinearLayout that pretends to be a ListView. But the problem is you are unable to take advantage of the "smart" loading/unloading of views that an adapter provides.

<ScrollView>
    <LinearLayout>

        <TextView/>
        <LinearLayout
            android:orientation="vertical" />    # add ListItems here

    </LinearLayout>
</ScrollView>


Idea #2 - Use a hacky ArrayAdapter, with a getView method similar to this:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if(position == 0)
        View view = inflater.inflate(R.layout.special_list_item, null);
    else
        View view = inflater.inflate(R.layout.regular_list_item, null);

    ...

    return vi;
}

Answer

dymmeh picture dymmeh · Aug 21, 2013

Simple. Just add a header view to your ListView

TextView textView = new TextView(context);
textView.setText("Hello. I'm a header view");

listView.addHeaderView(textView);