【问题标题】:Why we should re-assign values for a recycled convertView in getView()为什么我们应该在 getView() 中为回收的 convertView 重新分配值
【发布时间】:2015-02-25 04:12:54
【问题描述】:

例如(Xamarin c# 示例,但 Android java 的概念也相同): “数据”是保存数据的类

   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;
   }

这里对于列表中的每一行,都添加/刷新了 textView 和 imageView,这最初很好,但是当用户滚动和程序开始使用回收的视图时,为什么我们需要重新分配值(文本和图像)再次如果它已经存在于回收视图中,那将是一个过度的权利?如果我这样做怎么办:

   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;
   }

这对我来说很好用,但我担心的是我在这里或互联网上看到的许多示例中都没有看到任何这样的模式。

谢谢

更新:添加了“数据”类以更清楚地了解问题

【问题讨论】:

  • 在您的示例中,所有视图都是相同的,并且根据某些文本字段处于“活动”或“非活动”状态。所以是的,在你的例子中,几乎不需要回收视图。当然,如果您的用户的互联网连接速度非常慢,那么如果图像不在设备本地,则更新图像将需要很长时间,而如果您回收视图,则图像可以立即更新。

标签: c# android android-listview xamarin


【解决方案1】:

当一个 View 被回收时,它不一定是 sameAdapter 的项目(事实上,大多数时候,它不是 - 最常见的例子是“项目超出向下滚动时顶部的视图会重新插入底部”)。这就是为什么需要重新分配这些值,因为它们几乎总是依赖于 position 的值,这与上次使用此视图时不同。

您的示例有点简单,因为图像的文本始终相同,但在适配器视图的大多数用法中并非如此。

【讨论】:

  • 我已经编辑了我的问题以对代码进行一些更改。所以现在我的文字不同了。我把那个硬编码的值作为一个例子。我的想法是减少图像下载,如果它已经下载并在回收视图中可用。 (那我为什么要重新下载并分配它)
  • @shibin 不过,答案是一样的。当视图从getView() 返回时,它是为了记录(例如,2)。现在它被重新用于第 9 条记录。因此您需要更新其中显示的文本和图像。
  • 谢谢!我得到了它。现在,如果我执行以下操作会怎样://suppose if text.Text is the id field //this check will make sure that the reccylced view is matching with the current data if(text.Text == data.getID(position)) { text.Text = data.getText(position); imageView = GetImageAsynch(data.getURL(position)); } 我认为这个检查应该没问题?
  • @shibin 前提是文本永远不会在不同的位置重复,是的。
猜你喜欢
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多