NotifyDataSetChanged没有更新我的ListView
本文关键字:我的 ListView 更新 NotifyDataSetChanged | 更新日期: 2023-09-27 18:26:08
NotifyDataSetChanged()不会更新ListView,即使我正在重新读取序列化的xml文件。它只有在再次调用oncreate之后才会更新。读了一些Java代码,它告诉我重新填充我的listadapter,但这仍然不起作用。有什么想法吗?
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.Card, null);
listView = view.FindViewById<ListView>(Resource.Id.cardListView);
return view;
}
public override void OnResume()
{
base.OnResume();
List<string> nameList = new List<string>();
string documentsPath = Android.OS.Environment.ExternalStorageDirectory + "/Gate";
var cardPath = Path.Combine(documentsPath, "card.xml");
if (File.Exists(cardPath))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Card>));
StreamReader reader = new StreamReader(cardPath);
cardList = (List<Card>)serializer.Deserialize(reader);
reader.Close();
}
else
{
cardList = new List<Card>();
}
foreach (Card card in cardList)
{
nameList.Add(card.name);
}
var adapter = new ArrayAdapter<string>(this.Activity, Android.Resource.Layout.SimpleListItem1, nameList);
listView.Adapter = adapter;
adapter.NotifyDataSetChanged();
}
您应该只在OnCreate中创建一次适配器并将其存储
然后,在OnResume()中,只使用适配器更新值。AddAll(nameList)并调用NotifyDataSetChanged();