ListView onClick更新清除列表

ListView onClick update clears the list

我有以下代码应该删除被点击的项目:

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();
}

当我点击一个项目时,列表被清除并且没有任何显示。大小是正确的值,列表可以重建,但我无法让这段代码工作。 谢谢

与其每次都创建一个全新的 Adapter,你有没有想过简单地让你的 Adapter 成为一个成员变量并调用 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();

将您的列表和适配器定义为即时变量,并且您还必须通知适配器才能使删除生效, 试试这个,

        listview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            email_addresses.remove(position);
            adapter .notifyDataSetChanged();
        }
    });