Ketamaskinen Ketamaskinen - 15 days ago 5
Android Question

How to delete object from onclick in recyclerview?

I am trying to create my first Android application and im having trouble recognising the easiest way to delete objects shown in a list.

More specifically:

I have a recyclerView of objects and wants to be able to delete objects through an onClickListener in the list. I am thinking the easiest way would be to make the onClickListener recognise which index on the recyclerview is clicked and then do some objectList.remove(index), but i am not quite sure if that is possible?

Another way would be for the OnClickListener to recognise the name of the object i represents from at textView and iterate through my ObjectList, but that doesn't seem quite as efficient as the first.

How can i make my OnClickListener recognise which listitem it belongs to? Or is there another way i haven't been able to see?

Thanks in advance!

Answer

You need to implement the onClickListener inside the onCreateView() method of your recycler view adapter.

  View v = LayoutInflater.from(parent.getContext())
                         .inflate(R.layout.holder_layout, parent, false);
  final CustomViewHolder holder = new CustomViewHolder(v);
  holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override 
     public void onClick(View view) {
      int adapterPos = holder.getAdapterPosition();
      if (adapterPos != RecyclerView.NO_POSITION) {
        // now you can use adapterPos to get the item in your list
      }
    }
  });

This video will explain it better: https://youtu.be/imsr8NrIAMs?t=35m46s

Comments