Modifying Previous RecyclerView ViewHolders

Nathan Sokalski 4,111 Reputation points
2021-05-05T22:25:41.78+00:00

I have a RecyclerView in which when an item (ViewHolder) is clicked using the ItemClick event, I want to not only do something to the clicked item, but to a previous item. However, because the previous item may have been scrolled out of view, it may have been recycled, and I receive a NullReferenceException (which I would expect). But it does not seem like it was recycled, because when I scroll back to the previous item, it does not look like it is new (it does not look like it has been updated by OnBindViewHolder). How can I perform an action on an item that has been scrolled out of view if I cannot reference it, or why is it not being updated by OnBindViewHolder before being shown again?

Developer technologies .NET Xamarin
{count} votes

Accepted answer
  1. JessieZhang-MSFT 7,716 Reputation points Microsoft External Staff
    2021-05-07T08:08:12.007+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    why is it not being updated by OnBindViewHolder before being shown again?

    After updating the data of one item in code behind, once the item is visible in the screen, it will call function onBindViewHolder to update the UI.
    On the other hand, if it's not in the visible area of the screen, the ViewHolder will be occupied by some other item which is in the visible area of the screen.

    This is due to the ViewHolder reuse mechanism.

    You can override method OnViewRecycled to verify this.

        public override void OnViewRecycled(Java.Lang.Object holder)  
        {  
            base.OnViewRecycled(holder);  
    
            YourViewHolder holder1 = holder as YourViewHolder ;  
    
            System.Diagnostics.Debug.WriteLine("OnViewRecycled: " + holder1.CaptionTv.Text+"<---> position = "+ holder1.AdapterPosition);  
        }  
    

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.