trycatch
trycatch

Reputation: 304

Click event is invoked more than once in RecyclerView (xamarin android)

I wanna share this problem I had when i created a recycleView and it has a button in it that removes an item. Just in case someone out there also wasted his whole day trying to figure this one out.

whenever I clicked the button, it sometimes remove two items (invoked twice)

here is the code (simplified)

public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            MyView myHolder = holder as MyView;
            int IndexPosition = (Cards.Count - 1) - position;
            myHolder.tvTitle.Text = Cards[IndexPosition].Title;
            myHolder.tvSubTitle.Text = Cards[IndexPosition].SubTitle;
            myHolder.tvTime.Text = Cards[IndexPosition].Time;

            myHolder.mMainView.Click += (o, e) =>
            {
                 //delete the item, console.write("something")
            };
        }

to simplyfy, "something" is written twice..

Upvotes: 1

Views: 956

Answers (1)

trycatch
trycatch

Reputation: 304

first of all: DO NOT ADD DELEGATE ON CLICK EVENTS IN OnBindViewHolder

INSTEAD you must instead asign your click events in this method:

public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) 

for example

public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
            View row = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.CardView_proto,parent,false);

            TextView Title = row.FindViewById<TextView>(Resource.Id.cardview_textView_main);
            Button buttonCheck = row.FindViewById<Button>(Resource.Id.cardview_button_check);

            MyView view = new MyView(row) { tvTitle = Title };
            buttonCheck.Click += (o,e) => 
            { 
                       **//your method here won't be called twice**
            };
            return view;
};

Upvotes: 2

Related Questions