简体   繁体   中英

How to delete item from listview using own ArrayAdapter?

I Have problem, I want to delete a row frow listView and this element from ArrayList.

This is my new ArrayAdapter

private ExpenditureAdapter adapter = null;

and I adding to it data using:

adapter = new ExpenditureAdapter(this,R.layout.activity_show_list,addExpenditure.getExpidentures());
        setListAdapter(adapter);

It works correctly, but I want create OnItemClickListener and use it to delete data from listView and from ArrayList<Expenditure> , but how to do it ?

My effort:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                addExpenditure.getExpidentures().remove();
            }
        });

But ofc it doesn't work.How get index to delete this ?

Try this

 YourListView.setOnItemClickListener(new OnItemClickListener()
   {
      @Override
      public void onItemClick(AdapterView<?> adapter, View v, int position,
            long arg3) 
      {
              YourArrayList.remove(position);
            YourArrayAdapter.notifyDataSetChanged();
      }
   });

You almost have it working, change your listener to this:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         addExpenditure.getExpidentures().remove(position);
         parent.notifyDataSetChanged();
     }
});

Basically, if you are changing the underlying data of an adapter (your ArrayList), you need to notify the adapter so it can update the list accordingly. This will remove the item and then redraw the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM