Search code examples
androidlistviewandroid-activityheaderoncreate

Trying to add a HeaderView to ListView in android But I cant add


In my activity, I had a ListView. In that I am trying to add header view to list view looks not working to me. When i add header view using addHeaderView() method it throws

 java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called

When I comment out listView.addHeaderView(header);, it works fine. But i called addHeaderview() method before setAdapter() method. I cant figure out why this error occured. Let me know what error in my code.

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    TextView header= new TextView(this);
    header.setText("Header");
    ListView listView = (ListView)findViewById(R.id.list_view);
    listView.addHeaderView(header);
    List<String> list = new ArrayList<String>();
    for (int i = 0; i < 20; i++) {
        list.add("Row "+i);
    }
    listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list));

Solution

  • I got it guys. I had added android:entries attribute in xml file. So that setAdapter() called before addHeaderView() method.

            <ListView
                android:id="@+id/confess_list_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:entries="@array/sample_array"
                android:padding="@dimen/medium"
                android:layout_margin="@dimen/medium"
                android:background="#fbf8f8"
                android:scrollbars="none">
    
            </ListView>
    

    When I removed android:entries attribute from xml, Its working fine. Thanks @Bhavik Mehta.