Avoiding RecyclerView ViewHolder Events During Notify

Nathan Sokalski 4,116 Reputation points
2021-05-09T22:54:15.523+00:00

I have a RecyclerView whose ViewHolder contains elements with events (such as the TextChanged event of EditText). I have a point in my code in which I want to clear the item list & add new items (sort of start over). However, during this process the TextChanged event is being triggered for EditText(s) in ViewHolder I no longer need (that should just be used after being recycled). When I override OnViewRecycled, I detach these event handlers, but that doesn't seem to be helping. How can I prevent or detach events when calling NotifyDataSetChanged()?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,294 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,936 Reputation points
    2021-05-10T08:15:54.287+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    However, during this process the TextChanged event is being triggered for EditText(s) in ViewHolder

    Hi, njsokalski. I created a basic demo to test the function, the TextChanged event will not be triggered when clearing and adding new items. Here is the code of my project, please check it. If it doesn't work on your side, please share the related code to reproduce the issue.

       private async void MainActivity_Click(object sender, EventArgs e)  
       {  
           list.Clear();  
           list.Add(new model { ... });  
           ...  
           myadapter.NotifyDataSetChanged();  
       }  
    

    Custom ViewHolder class

       public class CustomViewHolder : RecyclerView.ViewHolder  
       {  
           public EditText Edit { get; private set; }  
         
           public _ViewHolder(View itemView) : base(itemView)  
           {  
               Edit = itemView.FindViewById<EditText>(Resource.Id.edit);  
               Edit.TextChanged += delegate  
               {  
                   //  
               };  
           }  
       }  
    

    Best Regards,

    Jarvan 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.