我有一个自定义适配器,这给我带来了问题。当我添加或编辑某些内容时,它会更新列表视图,但是删除时则不会。
我删除某物时的代码:
private ArrayList<Teams> m_orders = null;
private TeamsAdapter m_adapter;
private ListView lstv;
...
private void deleteTeam(int indexRemove){
hasKeys.remove(hasKeys.indexOf(m_orders.get(indexRemove).getTeamName()));
Menu.teams.remove(m_orders.get(indexRemove).getTeamName());
m_orders.remove(indexRemove);
m_adapter.notifyDataSetChanged();
}
我尝试使用Runnable,但没有成功。
private Runnable returnRes = new Runnable() {
@Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_adapter.notifyDataSetChanged();
}
};
我的onCreate方法:
lstv = findViewById(R.id.teamsList);
m_orders = new ArrayList<Teams>();
this.m_adapter = new TeamsAdapter(this, R.layout.row, m_orders);
lstv.setAdapter(this.m_adapter);
答案 0 :(得分:1)
您必须从Adapter类内的ArrayList中删除一个项目。因此,您需要在适配器类中编写删除函数。这样,便可以通过调用notifyDataSetChanged()
方法来删除项目并更新列表视图。
答案 1 :(得分:0)
您正在使用m_adapter
数据集创建m_orders
,但是您要从m_teams
数据集中删除项目,这没有意义,它们是不同的实例。
final List<Teams> mTeams = new ArrayList<>();
TeamsAdapter mAdapter;
onCreate() {
mAdapter = new TeamsAdapter(this, R.layout.row, mTeams);
ListView listView = (ListView) findViewById(R.id.teamsList);
listView.setAdapter(mAdapter);
}
addTeams(Collection<Teams> items) {
mTeams.addAll(items);
mAdapter.notifyDataSetChanged();
}
deleteTeam(int index) {
mTeams.remove(index);
mAdapter.notifyDataSetChanged();
}