我有以下代码可以删除点击的项目:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
email_addresses.remove(position);
String size = Integer.toString(email_addresses.size());
Log.d("Size: ", size);
//listView = (ListView) findViewById(R.id.email_list);
//ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, email_addresses);
//listView.setAdapter(adapter);
ArrayAdapter<String> adapter = new ArrayAdapter<>(mainAppContext, android.R.layout.simple_list_item_1, android.R.id.text1, email_addresses);
((ListView)parent).setAdapter(adapter);
parent.refreshDrawableState();
}
当我点击某个项目时,列表会被清除,并且不会显示任何内容。大小是正确的值,列表可以重建,但我无法使此代码工作。 谢谢
答案 0 :(得分:2)
您是不是每次都创建一个全新的适配器,而是考虑简单地将您的适配器变为成员变量并调用notifyDataSetChanged?
ArrayAdapter<String> adapter = new ArrayAdapter<>(mainAppContext, android.R.layout.simple_list_item_1, android.R.id.text1, email_addresses);
((ListView)parent).setAdapter(adapter);
变为:
mAdapter.notifyDataSetChanged();
答案 1 :(得分:1)
将列表和适配器定义为即时变量,并且还必须通知适配器以使删除受影响, 试试这个,
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
email_addresses.remove(position);
adapter .notifyDataSetChanged();
}
});