android - 当我们可以对静态变量做同样的事情时,为什么要使用 getTag/setTag

标签 android listview android-viewholder

我们知道当我们在列表/ GridView 中使用 ViewHolder 模式时,我们使用 setTag/getTag 来获取信息。但是在我的代码中,如果我通过简单的静态 ViewHolder 替换它,它可以正常工作并正确显示图像。那么,getTag()/setTag()有什么用呢?

@Override
public View getView(int pos, View convertView, ViewGroup parent) {
   LayoutInflater inflater = LayoutInflater.from(mContext);
   if(convertView == null) {
      convertView = mInflater.inflate(R.layout.card_view, parent, false);
      ViewHolder.image = (ImageView)convertView.findViewById(R.id.myImage);
   }
   // ....
   // ... attach image here. Via library or directly.
   // As an example I'm using Picasso
   Picasso.with(mContext).load(mThumbIds[pos]).into(ViewHolder.image);

   return convertView;
}

// static ViewHolder pattern.
private final static ViewHolder {
  static final ImageView image;
}

private int mThumbIds[] = {
 R.drawable.sample1, R.drawable.sample2 // etc...
};

如果您需要,这里是 xml: card_view.xml

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardElevation="1dp"
    android:clickable="true"
    app:cardCornerRadius="2dp"
    android:foreground="?android:attr/selectableItemBackground">

 <ImageView
            android:id="@+id/card_view"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:src="@drawable/placeholder"
            android:scaleType="centerCrop"/>

</android.support.v7.widget.CardView>

最佳答案

But here in my code if I replace this via simple static ViewHolder, it works fine

不,它没有。

首先,你像筛子一样泄漏内存。

其次,一旦用户滚动,您的方法就会失效,因为您将开始更新错误的 ImageView。您的代码依赖于行永远不会被回收这一事实,只有当您的 ListView/GridView 不需要太多滚动,或者如果您有一个严重的试图完全避免 View 回收的困惑适配器。

关于android - 当我们可以对静态变量做同样的事情时,为什么要使用 getTag/setTag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32355231/

相关文章:

android - SoapFault - 错误代码 : 'soap:Server' faultstring: 'System. Web.Services.Protocols.SoapException:

java - 如何在 Android 中使用 onListItemClick 在 listView 中打开带有联系人姓名的联系人详细信息卡?

java - 操作 ArrayAdapter 时出现 ArrayIndexOutOfBoundsException

android - RecyclerView 中的项目未按预期对齐

java - Android - "No enclosing instance of type ' some.abstract.class.name'类在范围内“扩展时出错

android webview 不使用 WebViewClient 显示视频

java - android中上传文件到php服务器时如何设置字符串参数

android - Android应用程序组合

android - 如何覆盖 Android ListView 快速滚动条外观

android - 如何连接 RecyclerView 的 ViewHolder 和容器 Activity/fragment ?