Cannot add header view to list — setAdapter has already been called

自作多情 提交于 2019-11-27 14:37:52

On android 2.3, add header after setAdapter (even if you have added early, then removed) will throw an exception. To hide or show a header dynamically, use setVisibility(). How? You can see Hiding header views.

Cannot add header view to list -- setAdapter has already been called. which you can see, the myList.addHeaderView(header) must be execute before myList.setAdapter(adapter);

Try this..

dataAdapter = new MyCustomAdapter(this, R.layout.results_list_item, searchedResults);
myList.addHeaderView(header);
myList.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();

you can add FrameLayout as header view before setting adapter and dynamically add/remove view in FrameLaypout

I had the same problem today. I have multiple ListViews.. With the information from the first, it builds the list of the next one and everyone has setAdapter in it. For me, the best solution was to put

setListAdapter(null);

on top of the function, where I inflate the Header. I hope this helps..

If you were used android:entries in ListView in xml file, Its called setAdapter() method before addHeaderView. So remove android:entriesattribute from ListView in xml layout file. It will be work.

After I set

final ViewGroup header = (ViewGroup) inflater.inflate(R.layout.item, listView, false);
listView.addHeaderView(header, null, true); 

before

listView.setAdapter(adapter);

a problem still appeared. Then I made Build > Clean Project.

After so much efforts i got solution for my side i hope this will helps someone too

i already set adpater at the last (after view added) but dont know why i was suffring from same error so here i did something like this code

// Set View here
View view = getLayoutInflater().inflate(R.layout.navigation_header,null);
mDrawerList.addHeaderView(view);
// init your adapter
adapter1 = new YourListAdapter(getApplicationContext(),blabla);
// set adapter into handler
Handler handler = new Handler();
handler.postDelayed(new Runnable() {        
   @Override
  public void run() {
  // TODO Auto-generated method stub
  mDrawerList.setAdapter(adapter1);
  }
}, 100);

I put my adapter in to handler sometime it happends that adapter set faster then view so this code enough for me to solve this exception. :)

vamsiampolu

I have used the following code in my sample application to set a ListView header:

ListView lv = getListView();
View headerView = getLayoutInflater().inflate(R.layout.layout_header, null, false);
lv.addHeaderView(headerView);
final TumblrDB db = new TumblrDB(this);
c = db.query();
startManagingCursor(c);
adapter = new CustomCursorAdapter(this, R.layout.layout_del, c, new String[]{TumblrDB.DATE, TumblrDB.DESC}, new int[]{R.id.txt_a, R.id.txt_b});
lv.setAdapter(adapter);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!