【问题标题】:ListView not updating after item deletion删除项目后 ListView 不更新
【发布时间】:2014-03-12 19:35:20
【问题描述】:
我正在从适配器中删除一个元素,该元素应该被删除并在 UI 中,并且 ListView 已刷新。发生的情况是该元素确实从适配器中删除,但仍然保留在列表中,直到手动刷新列表(打开另一个片段,然后返回列表片段并繁荣!删除的元素确实不再在列表)。但我希望立即刷新列表!
这是我用于删除的内容:
ClockAdapter myAdapter = (ClockAdapter)listView.getAdapter();
Alarm myAlarm = myAdapter.getItem(selectedPosition);
MyAlarmManager.deleteAlarm(myAlarm);
myAdapter.notifyDataSetChanged();
将不胜感激任何帮助!
【问题讨论】:
标签:
android
listview
android-fragments
android-listview
android-adapter
【解决方案1】:
您还需要从Adapter 中删除该项目。调用:
ClockAdapter myAdapter = (ClockAdapter)listView.getAdapter();
//...
Alarm myAlarm = myAdapter.getItem(selectedPosition);
myAdapter.remove(myAlarm);
myAdapter.notifyDataSetChanged();
【解决方案2】:
notifyDataSetChanged () - 医生说,
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
因此,调用它会告诉适配器传递给它的数据(在您的情况下是警报列表)已被修改,因此它应该刷新。这意味着您的适配器将再次从您附加到它的数据结构中读取和加载数据。
因此,为了让适配器反映删除,您也必须从该列表中删除它。
假设你有一个ArrayList<Alarm> called myArrayAlarm 附加到你的适配器,那么你应该从中删除它。
你可以打电话,
myArrayAlarm.remove(myAlarm)
myAdapter.notifyDataSetChanged();
菲利普的方式也是正确的。 :)
【解决方案3】:
删除项目后总是添加以下两行
notifyDataSetChanged();
notifyDataSetInvalidated();