【问题标题】:Long click remove item from android listview [duplicate]长按从android listview中删除项目[重复]
【发布时间】:2018-02-25 01:10:18
【问题描述】:

我应该在onItemLongClick 函数中写什么,以便在长按时从列表视图中删除一个项目。下面是代码:

public class Favorites extends AppCompatActivity {

DBConnection db = new DBConnection(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_favorites);

     ListView listView = (ListView) findViewById(R.id.empList);
     ArrayList<String> arrayList = db.getAllRecords();
     listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,arrayList));

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                        int position, long id) {



            return false;
        }

【问题讨论】:

  • 要将其从ListView 中删除,您只需在ArrayList 上调用remove(position),然后在ArrayAdapter 上调用notifyDataSetChanged()。但我不认为这就是你想要做的,不是吗?

标签: java android


【解决方案1】:

您应该为 listView setOnItemLongClickListener 并定义 adapter 以在删除项目时更新数据

ListView listView = (ListView) findViewById(R.id.empList);
    final ArrayList<String> arrayList = db.getAllRecords();
    final ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,arrayList);
    listView.setAdapter(adapter);

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            arrayList.remove(i);
            adapter.notifyDataSetChanged();
            return true;
        }
    });

【讨论】:

  • 非常感谢@nhonnq,您的代码运行良好,但是当我再次运行代码时,我发现我删除的相同项目仍然存在。换句话说,在运行时,我可以从列表中删除任何项目。但是当我关闭应用程序并再次运行它时,我会再次看到所有项目。
  • 您只需删除 arrayList 中的项目,因此当您再次运行应用程序时,arrayList 已到达 db (db.getAllRecords())。所以删除时需要删除数据库中的数据
【解决方案2】:

在我的例子中,我使用了一个自定义适配器类作为将数据连接到 ListView 之间的一种方式。在这种情况下,它将类似于以下内容:

Adapter adapter = new Adapter(this, arrayList);
String s = (String) arrayList.get(position);
arrayList.remove(s);
adapter.notifyDataSetChanged();

也看看这个 repo:

https://github.com/CarmenDelessio/Hour8Application/tree/master/app/src/main/java/com/bffmedia/hour8application

特别是 BaseAdapterActivity.java 值得用作模型。

【讨论】:

  • 不幸的是,它不起作用。它给了我错误:无法解决方法 notifyDataSetChanged()
  • 它必须调用 Adapter 的对象。
【解决方案3】:

你可以试试这个从你的数组列表中删除一个元素

arrayList.remove(position);

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多