Reputation: 717
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));
Upvotes: 1
Views: 589
Reputation: 1730
It worked for me like this :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_id);
//code to add header and footer to listview
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);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, numbers);
listView.setAdapter(adapter);
}
Upvotes: 0
Reputation: 717
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.
Upvotes: 2
Reputation: 174
Try like this:
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);
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
Upvotes: 0