Search code examples
androidlistadapter

have a TextView with a layout determined a ListAdapter


I have a screen where I just simply display the list of items. I have used setListAdapter(new ArrayAdapter<String>(ClassListActivity.this,android.R.layout.simple_list_item_1,getItems));
Now we dont have to create a separate xml layout for this right. But now I want to have a TextView that is the heading of this list may be saying "myItems"..When I try to link a xml layout with this activity, my application stops. and when I try to create a dynamic TextView, this way TextView tv = new TextView(this); and set text in it later. I dont get any errors but I get no results too just the old list no heading..

what should I do? thanks


Solution

  • You have to create your own XML layout for the ListAdapter. Put the TextView as the heading at the top followed by a ListView widget with the id @android:id/list.

    See more details here: ListActivity

    This one should work:

    <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="vertical"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:paddingLeft="8dp"
         android:paddingRight="8dp">
    
     <TextView android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:background="#FF0000"
               android:text="My list"/>
    
     <ListView android:id="@android:id/list"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:background="#00FF00"
               android:layout_weight="1"
               android:drawSelectorOnTop="false"/>
    
     </LinearLayout>