[英]Custom adapter size 0 after notifyDataSetChanged()
我有一个ListView,一个ArrayList和一个扩展ArrayAdapter的MaterielAdapter。 我的问题是,调用notifyDataSetChanged()不会更新我的ListView ...我花了3个小时尝试在SO上解决所有类似问题,但对我而言却没有效率。
private ListView lvMateriels;
private ArrayList<Materiel> materiels = new ArrayList<>();
...
lvMateriels = new ListView(this);
lvMateriels.setAdapter(new MaterielAdapter(this, R.layout.object_line,materiels));
...
materiels.add(new Materiel());
((MaterielAdapter)lvMateriels.getAdapter()).notifyDataSetChanged();
我的收藏集包含所有对象,但listview从不刷新,也没有适配器...
您甚至可能没有将ListView添加到活动视图中。 建议您不要在布局xml中定义一个listview,而不是执行新的Listview(this),例如:
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
然后在您的活动中:
lvObjects = (ListView) findViewById(R.id.listview);
找出解决方案
我的问题是我将ArrayList设置为另一个ArrayList
materiels = getMateriels() // getMateriels() returns an ArrayList<Materiel>
似乎将新对象设置为列表不起作用,我最终做了以下操作:
materiels.clear();
materiels.addAll(getMateriels());
顺便说一下,对于那些需要在其ListView中添加标头的人,您必须像这样:
((YourAdapter)((HeaderViewListAdapter)yourListView.getAdapter()).getWrappedAdapter()).notifyDataSetChanged();
库存您的适配器,您的适配器也将成为您的清单。
MaterialAdapter adapter = new MaterialAdapter(this,
R.layout.object_line);
lvObjects = new ListView(this);
lvObjects.setAdapter(adapter);
...
adapter.add(new Object());
adapter.notifyDataSetChanged();
Currenlty您的适配器,不知道他需要使用您传入参数的列表。 但是您扩展了ArrayAdapter,这意味着您的适配器是一个列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.