Android recycler view item click listener from Activity or Fragment

Android recycler view item click listener from Activity or Fragment

First Create an interface . NotfallKontakteEntity is Model of list items


public interface OnItemClickListener {
    void onItemClick(NotfallKontakteEntity item);
}

Then in adapter define and create constructor with click listener

public  OnItemClickListener listener;

public NotfallKontakteAdapter(List<NotfallKontakteEntity> notfallKontakteEntityList, OnItemClickListener listener) {
this.notfallKontakteEntityList = notfallKontakteEntityList;
this.listener = listener;
}

Now just declare it any click item view OnClickListener . Must add the item position as parameter.

  userHolder.delete.setOnClickListener(new View.OnClickListener() {
   @Override
    public void onClick(View v)
    {
      
   listener.onItemClick(notfallKontakteEntityList.get(position));
           
 }
 });

Now time to user this click listener. We can use anywhere in our fragment or activity

     recyclerView.setAdapter(NotfallKontakteAdapter(contactList, object : OnItemClickListener {
            override fun onItemClick(item: NotfallKontakteEntity) {
               Toast.makeText(context, contactList.id.toString(), Toast.LENGTH_LONG).show()


            }
        }))

Leave a Reply

Your email address will not be published. Required fields are marked *