为什么在使用静态变量时可以使用getTag / setTag

时间:2015-09-02 13:58:21

标签: android listview android-viewholder

我们知道在列表/网格视图中使用getTag()/setTag()模式时,我们使用setTag / getTag来获取信息。但是在我的代码中如果我通过简单的静态ViewHolder替换它,它工作正常并正确显示图像。那么,@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... }; 使用了什么?

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

以下是您需要的xml: 的 card_view.xml

php_sapi_name()

1 个答案:

答案 0 :(得分:1)

  

但是在我的代码中,如果我通过简单的静态ViewHolder替换它,它可以正常工作

不,它没有。

首先,你是像筛子一样泄漏记忆。

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