gpt4 book ai didi

android - ListView 未使用 notifydatasetchanged() 调用进行更新

转载 作者:可可西里 更新时间:2023-11-01 18:55:41 27 4
gpt4 key购买 nike

这是我的代码

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


ArrayList<SClass> Monday = new ArrayList<SClass>();

SClass s1=new SClass();
s1.sName="samp";
s1.salary=1000;
Monday.add(s1);
temp=Monday;
adapter = new CustomAdap(this, temp);
listview.setAdapter(adapter);

上面的代码工作正常。但是当我把我的代码改成这个时

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


adapter = new CustomAdap(this, temp);

SClass s1=new SClass();
s1.sName="samp";
s1.salary=1000;
Monday.add(s1);
temp=Monday;

listview.setAdapter(adapter);
adapter.notifyDataSetChanged();

Listview 不显示任何内容。问题是什么?

最佳答案

看起来您正在更改用于初始化适配器的集合。我会以这种方式更改您的代码:

// initial setup
listview =(ListView) findViewById(R.id.lv1);
ArrayList<SClass> Monday = new ArrayList<SClass>();
adapter = new CustomAdap(this, Monday);
listview.setAdapter(adapter);

// change your model Monday here, since it is what the adapter is observing
SClass s1=new SubjectClass();
s1.sName="samp";
s1.salary=1000;
Monday.add(s1);

// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();

请注意,如果您的 CustomAdap 是 ArrayAdapter 的子类,您也可以这样做

// change your array adapter here
SClass s1=new SubjectClass();
s1.sName="samp";
s1.salary=1000;
adapter.add(s1);

// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();

编辑:感谢您的评论,我更了解您现在想做什么。您可能希望让适配器用您的不同 ArrayLists 替换它的内容。我会让您的 CustomAdap 成为 ArrayAdapter 的子类。

然后你可以这样使用它:

// replace the array adapters contents with the ArrayList corresponding to the day
adapter.clear();
adapter.addAll(MONDAY);

// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();

关于android - ListView 未使用 notifydatasetchanged() 调用进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9747553/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com