[英]ListView items aren't updating with notifyDataSetChanged()
Apparently the notifyDataSetChanged()
only updates the visible items in the listview
, I have a system that changes the background color of an item when its clicked (to dkgray), and I set everything else to transparent(the default), however other items that aren't visible remain selected(dkgray) (I only want the currently selected item to be dkgray). 显然
notifyDataSetChanged()
仅更新listview
的可见项,我有一个系统,可以在单击(更改为dkgray)项目时更改其背景颜色,并将其他所有项目设置为透明(默认),但是将其他所有项目设置为透明不可见,保持选中状态(dkgray)(我只希望当前选中的项目为dkgray)。 Is there a way to force notifyDataSetChanged()
to update all items. 有没有一种方法可以强制
notifyDataSetChanged()
更新所有项目。
Here's example: 例子如下:
//makes all item backgrounds transparent
public void resetListViewBackground(){
for (int i = 0; i < listView.getChildCount(); i++){ //parent.getChildCount()
listView.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
}
//reloads the listview
private void reloadListView() {
listItems.clear();
adapter.notifyDataSetChanged();
listView.invalidateViews();
ArrayList<HashMap<String, String>> notesArrayList = dbTools.getAllNotes();
for (int i = 0; i < notesArrayList.size(); i++){
String temp = "";
if (notesArrayList.get(i).get("note").length() > 51){
temp = notesArrayList.get(i).get("note").substring(0,50).toString() + "...";
} else {
temp = notesArrayList.get(i).get("note").toString();
}
listItems.add(temp);
adapter.notifyDataSetChanged();
}
}
Everywhere I call resetListViewBackground()
, I call reloadListView()
after. 我在所有地方调用
resetListViewBackground()
,之后都调用reloadListView()
。 And this is what I use to highlight the selected item. 这就是我用来突出显示所选项目的方法。
view.setBackgroundColor(Color.DKGRAY);
Also, the most common occurrence of this problem is that every 6th item is highlighted. 同样,此问题最常见的情况是每第6个项目都会突出显示。 The
listview
only shows about 4 items at a time. listview
仅显示约4个项目。
The getChildCount()
method won't work for all list items as view recycling is done. 由于视图回收已完成,因此
getChildCount()
方法不适用于所有列表项。 Astral is right as he writes in the comments. Astral在评论中写道是正确的。
1) Create a custom adapter.(See http://windrealm.org/tutorials/android/listview-with-checkboxes-without-listactivity.php ) 1)创建一个自定义适配器。(请参阅http://windrealm.org/tutorials/android/listview-with-checkboxes-without-listactivity.php )
2)Inside the onListItemClick
listener's onItemClick()
method, call your adapter's notifyDataSetChanged()
method(whenever the user clicks a list item). 2)在
onListItemClick
侦听器的onItemClick()
方法内,调用适配器的notifyDataSetChanged()
方法(无论用户何时单击列表项)。
I modified the project that I mentioned and posted it on my Dropbox.(Just import it in Eclipse and run). 我修改了我提到的项目并将其发布到我的Dropbox中(只需将其导入Eclipse并运行)。 Check it out at https://www.dropbox.com/s/gchccjzpkxk8n2z/Planets_modified.zip
在https://www.dropbox.com/s/gchccjzpkxk8n2z/Planets_modified.zip中查看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.