无法刷新ListView与SimpleAdapter
问题描述:
我想添加一个新的条目到我的列表视图并刷新它仍然显示在列表视图中的旧条目。以前我是用ArrayAdapter我是能够通过使用无法刷新ListView与SimpleAdapter
adapter.notifyDataSetChanged();
添加新条目之后刷新但是我无法使用以上SimpleAdapter的代码。任何建议? 我已经尝试了几个解决方案,但迄今没有任何工作。
下面是我使用的是不添加条目代码:如果您beta3
方法真的是你的函数将新条目添加到您的ListView
void beta3 (String X, String Y){
//listview in the main activity
ListView POST = (ListView)findViewById(R.id.listView);
//list = new ArrayList<String>();
String data = bar.getText().toString();
String two= data.replace("X", "");
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String,String> event = new HashMap<String, String>();
event.put(Config.TAG_one, X);
event.put(Config.TAG_two, two);
event.put(Config.TAG_three, Y);
list.add(event);
ListAdapter adapter = new SimpleAdapter(this, list, R.layout.list,
new String[]{Config.TAG_one, Config.TAG_two, Config.TAG_three},
new int[]{R.id.one, R.id.two, R.id.three});
POST.setAdapter(adapter);
}
答
:它会设置一个新的适配器每次打电话时都会列出一个新名单。所以这总是会导致一个ListView
包含一个条目。在退出beta3
方法后,对该列表的引用消失。
您必须重用list
实例变量。将ArrayList<HashMap<String,String>> list
放在课堂/活动范围内,并将其初始化为一次(例如onCreate()
)。
另一个问题是,您使用ListAdapter
变量作为参考SimpleAdapter
实例。 ListAdapter
是一个不提供notifyDataSetChanged
方法的接口。您应该使用SimpleAdapter
变量。
下面是一个例子:
public class MyActivity {
ArrayList<HashMap<String,String>> list;
SimpleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
ListView POST = (ListView)findViewById(R.id.listView);
list = new ArrayList<HashMap<String, String>>();
adapter = new SimpleAdapter(this, list, R.layout.list,
new String[]{Config.TAG_one, Config.TAG_two, Config.TAG_three},
new int[]{R.id.one, R.id.two, R.id.three});
POST.setAdapter(adapter);
}
void beta3 (String X, String Y){
String two = ""; // adapt this to your needs
...
HashMap<String,String> event = new HashMap<String, String>();
event.put(Config.TAG_one, X);
event.put(Config.TAG_two, two);
event.put(Config.TAG_three, Y);
list.add(event);
adapter.notifyDataSetChanged();
}
}
好像的[本]重复(http://*.com/questions/9733572/android-adding-extra-item-on-listview)。 你如何尝试将项目添加到列表? – gus27