notifyDataSetChanged() 后自定义适配器大小为 0

Custom adapter size 0 after notifyDataSetChanged()

我有一个 ListView、一个 ArrayList 和一个扩展 ArrayAdapter 的 MaterielAdapter。我的问题是调用 notifyDataSetChanged() 不会更新我的 ListView...我花了 3 个小时在 SO 上尝试所有类似的问题,但 none 对我来说很有效。

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();

我的 collection 拥有所有 objects 但列表视图从不刷新,适配器也不...

储存您的适配器,您的适配器也将成为您的清单。

MaterialAdapter adapter = new MaterialAdapter(this, 
R.layout.object_line);

lvObjects = new ListView(this);
lvObjects.setAdapter(adapter);
...
adapter.add(new Object());
adapter.notifyDataSetChanged();

当前你的适配器,不知道他需要使用你传入参数的列表。但是你扩展了ArrayAdapter,这意味着你的适配器是一个列表。

您可能甚至没有将 ListView 添加到 activity 视图。与其使用 new Listview(this),我建议您在布局中定义一个列表视图 xml 类似于:

 <ListView
     android:id="@+id/listview"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>

然后在你的 activity:

lvObjects = (ListView) findViewById(R.id.listview);

找到解决方案

我的问题是我将我的 ArrayList 设置为另一个 ArrayList

materiels = getMateriels() // getMateriels() returns an ArrayList<Materiel>

看来在列表中设置一个新的object是行不通的,我最后做的是:

materiels.clear();
materiels.addAll(getMateriels());

顺便说一句,对于那些需要 header 到他们的 ListView 中的人,您必须这样做 :

((YourAdapter)((HeaderViewListAdapter)yourListView.getAdapter()).getWrappedAdapter()).notifyDataSetChanged();