How do I delete an item from my custom base adapter?

后端 未结 5 1662
半阙折子戏
半阙折子戏 2020-12-16 22:29

I am extending BaseAdapter to make a custom listview row. I have context menu that opens everytime a user holds on the row and prompts if he wants to delete it. However how

相关标签:
5条回答
  • 2020-12-16 22:42

    You should add a Listener on your adapter to handle the delete event.

    public YourAdapter(Context context, List<T> rows, View.OnClickListener deleteListener) 
    { ... }
    

    And on your getView() method set the listener

    yourBtn.setOnClickListener(this.deleteListener);
    

    You can add a value on the btn tag to identifiy the current row :

    yourBtn.setTag(position);
    

    Finally, on your Activity, your listener will fire with the current position in tag. You can then use the previous answer to update your adapter and refresh your listview.

    0 讨论(0)
  • 2020-12-16 22:48

    In your BaseAdapter, add the code:

    public View getView(final int position, View convertView, ViewGroup parent) {
        View v = convertView;
    
        LayoutInflater layoutInflater = LayoutInflater.from(this.context);
        v = layoutInflater.inflate(R.layout.items, null);
    
        TextView buttonDelete = (TextView) v.findViewById(R.id.buttonDelete);
        buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                item.remove(position);
                notifyDataSetChanged();
            }
        });
        return v;
    }
    
    0 讨论(0)
  • 2020-12-16 22:49
    1. remove item from items
    2. call BaseAdapter.notifyDataSetChanged(). Then listview will be redrawn and target row will be removed from screen.
    0 讨论(0)
  • 2020-12-16 23:00

    To delete, you'll need to do 2 things:

    1. Call .remove() on your ArrayList (items).
    2. Call .notifyDataSetChanged() on the instance of your MyListAdapter class (mListAdapter).
    0 讨论(0)
  • 2020-12-16 23:02

    You do not delete from the adapter ! You delete from the items ! and the adapter is between your items and the view. From the view you can get the position and according the position you can delete items. Then the adapter will refresh you views.

    That means you need to do something like this

     items.remove(position);
    adapter.notifyDataSetChanged()
    
    0 讨论(0)
提交回复
热议问题