Dismissile
Dismissile

Reputation: 33071

RecyclerView Click event

I have created a RecyclerView adapter and I'm trying to start an activity when a row is clicked:

public override OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
    MyViewHolder viewHolder = (MyViewHolder)holder;

    viewHolder.MyView.Click += (sender, e) =>
    {
        var context = viewHolder.MyView.Context;
        var intent = new Intent(context, typeof(DetailActivity));
        context.StartActivity(intent);
    }
}

When I click the first row it will take me to the activity like I want. If I scroll down so that the first row is rebound and then scroll back to the top again and then click the first row then my Click event fires twice. Once for the first row that was bound and then again for a row that was bound when I scrolled.

Is there an event you need to handle to unregister the click events?

Upvotes: 2

Views: 3181

Answers (1)

Jared
Jared

Reputation: 702

I believe the standard pattern is to setup your clickhandlers in the constructor of the ViewHolder. Then in OnBindViewHolder, you update the Views/Data inside the ViewHolder.

Something like this (not compiled code):

Adapter:

public override OnBindViewHolder()
{
   MyViewHolder viewHolder = (MyViewHolder)holder;

   viewHolder.SetData(whatever data you care about);
}

MyViewHolder:

public MyViewHolder(View view) : base(view)
{
    MainView = view;
    MainView.Click += (sender, e) =>
    {
        var context = MainView.Context;
        var intent = new Intent(context, typeof(DetailActivity));
        context.StartActivity(intent);
    }
}

Doing it this way keeps the Adapter cleaner by putting business logic in the ViewHolder, and also prevents your click handlers from being constantly setup and torn down as you scroll.

Upvotes: 4

Related Questions