我看到关于notifyDataSetChanged()有许多问题。我已经浏览了其中的许多解决方案,但没有任何解决方案适用于我。Android适配器notifyDataSetChanged()不清除以前的列表
我使用ArrayList来设置我的列表,并且在我的ArrayList更新后,我运行了notifyDataSetChanged()。新的列表被添加到前一个列表中。
可以说第一个列表是a,b,新列表是a,b,c。我最终得到的是a,b,a,b,c。 并且每次更新时都会再次出现新列表。我试过其他如invalidate(),适配器clear(),refreshDrawableState()等,并没有任何工作。
预先感谢您。
这里是简化的代码,即使在更改.xml文件中的代码后,更改MainActivity将Activity扩展为ListActivity的注释也会使程序崩溃。
public class MainActivity extends Activity
{
ArrayList<String> names = new ArrayList<String>();
ArrayAdapter arrayAdapter = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv1 = (ListView) findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, names);
lv1.setAdapter(arrayAdapter);
}
//code here to edit the ArrayList names.
public void onResume()
{
super.onResume(); // Always call the superclass method first
//the activity need to be updated everytime it resumes.
arrayAdapter.notifyDataSetChanged();
}
}
检查你的名字。 –
可能问题出在你正在更新ArrayList的代码中。你能分享吗? ArrayList在某些方面很棘手,如何替换整个列表内容并不明显。在放置新元素之前,您是否调用clear()? – sandrstar
我不清楚你是否希望新列表包含a,b,a,b,c或只是a,b,c。你是否正确地更新了'ArrayList'的内容? – Spinner