简体   繁体   中英

Why we should re-assign values for a recycled convertView in getView()

For example (Xamarin c# example, but concept is same for Android java also): "data" is the class which holds the data

   public override View getView (int position, View convertView, ViewGroup parent){
       if( convertView == null ){

           convertView = inflater.inflate(Resource.layout.my_list_item, parent, false);
       }
        //just for example , hence avoiding ViewHolder here
        var textView = convertView.FindViewById<TextView>(Resource.Id.textView2);
        var imageView = convertView.FindViewById<ImageView>(Resource.Id.feedImageView);

       text.Text = data.getText(position);
       imageView = GetImageAsynch(data.getURL(position));

       return convertView;
   }

Here for every rows in the list, both textView and imageView is added/refreshed, which is fine initially, however when user scrolling and when program start using the recycled views, why do we need to re-assign the values (text and image) again if it is already present in the recycled views, that would be an over head right? What if I do as below:

   public override View getView (int position, View convertView, ViewGroup parent){
       if( convertView == null ){

           convertView = inflater.inflate(R.layout.my_list_item, parent, false);
       }
        //just for example , hence avoiding ViewHolder here
        var textView = convertView.FindViewById<TextView>(Resource.Id.textView2);
        var imageView = convertView.FindViewById<ImageView>(Resource.Id.feedImageView);

       //this means if (recycled) view is empty, then only update the view
       if(text.Text == "")
       {
         text.Text = data.getText(position);
         imageView = GetImageAsynch(data.getURL(position));
       }

       return convertView;
   }

This is working fine for me, but my concern is I didn't see any such pattern in many examples I see here or in the internet.

Thank you

Update: Added "data" class to have more clarity on the question

When a View is recycled, it's not necessarily for the same item of the Adapter (indeed, most of the time, it's not -- the most common example is "item goes outside the view at the top as you scroll down, is reinserted at the bottom"). That's why the values need to be reassigned, because they almost always depend on the value of position , which will not be the same as the last time this view was used.

Your example is a bit trivial insofar as the text of the image are always the same, but this is not the case in most usages of Adapter views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM