列表视图未使用 notifydatasetchanged() 调用进行更新
Posted
技术标签:
【中文标题】列表视图未使用 notifydatasetchanged() 调用进行更新【英文标题】:listview not updating with notifydatasetchanged() call 【发布时间】:2012-04-02 14:28:48 【问题描述】:这是我的代码
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 不显示任何内容。这是什么问题?
【问题讨论】:
如果您提供 CustomAdap 和 Monday 的来源,以及声明 Monday 的位置,这会更清楚。 我已经为 customadap 添加了代码,monday 是一个 SClass 的 Arraylist @TariqIbrahim 你能看到***.com/questions/28148618/… 【参考方案1】:看起来您正在更改初始化适配器的集合。我会以这种方式更改您的代码:
// 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();
【讨论】:
我使用 temp 的目的是因为,我有不同的数组列表,星期一星期二等。我想在不同的日子复制显示不同的内容,这就是为什么我使用一个数组列表 temp.and temp可以从周一、周二等任何一个数组列表中分配值。 没有名为addAll的方法 您的 CustomAdap 必须继承 ArrayAdapter,其中包括clear
和 addAll
。像public class CustomAdap extends ArrayAdapter<SClass>
这样的东西。请参阅developer.android.com/reference/android/widget/… 以供参考。
我可以使用 for 循环。但这会增加我的代码长度。任何与 AddAll 类似的方法都会有所帮助:)
我的自定义适配器扩展了 ArrayAdapter【参考方案2】:
为什么它在第一个代码中起作用?
--- 因为您将值设置为 temp
列表并将其传递给 adapter
并将其显示到 listview
中。
为什么不能在第二个代码中工作?
--- 因为您在将值设置为 temp 之前将 temp 设置为适配器 其次,当您将新值设置为 temp 时,您的适配器类可能无法获得更新的值 ..因为 temp 不是公共的或不在类级别或不是静态的.. 将临时声明放在根级别并尝试。
如果您收到任何警告,请尽可能多地显示您的完整代码和 Logcat。
【讨论】:
根级别是什么意思? @MKJParekh 很好的解释。它帮助了我。谢谢【参考方案3】:在正确的 xml 文件中检查指向您引用视图的链接。或者至少检查该xml文件是否存在。
【讨论】:
【参考方案4】:您使用的是什么适配器?这显然是您在临时变量中设置数据后适配器没有更新的情况。
【讨论】:
那么我们怎样才能得到呢?以上是关于列表视图未使用 notifydatasetchanged() 调用进行更新的主要内容,如果未能解决你的问题,请参考以下文章
列表视图未使用 notifydatasetchanged() 调用进行更新