3

在与方法一起存储的 ViewHolder 中保留 Activity 的句柄是否安全setTag

我发现这个问题声称存储对 Activity 的引用可能会导致内存泄漏,但它已在 Android 4.0 中得到修复:https ://code.google.com/p/android/issues/detail?id=18273

具体来说,我想知道拥有一个看起来像这样的 ViewHolder 是否安全:

class MyHolder {
  private Context context; // <<-- is this safe to keep here??
  private TextView textView;

  public MyHolder(Context context) {
    this.context = context;
  }

  public void populate(Doc doc) {
    textView.setText(context.getString(doc.getTextId()));
  }

  public View inflate(ViewGroup parent) {
    View view = LayoutInflater.from(parent.getContext()).inflate(
        R.layout.doc_item, parent, false);

    textView = (TextView)view.findViewById(R.id.doc_item_text);

    return view;
  }
}

在我的 ArrayAdapter 中使用 getView 方法,如下所示:

@Override
public View getView(int position, View row, ViewGroup parent) {

    Doc doc = getItem(position);

    MyHolder holder;
    if (row != null) {
        holder = (MyHolder) row.getTag();
    } else {
        holder = new MyHolder(getContext());
        row = holder.inflate(parent);

        row.setTag(holder);
    }

    holder.populate(doc);

    return row;
}

(代码是实际代码库的简化版本,只是为了理解这一点。)

我见过的示例代码都没有存储对除持有者中的视图之外的任何内容的引用。我想知道这是巧合还是设计。

4

1 回答 1

4

不管在这种情况下是否安全,最好将 Context 引用保持在最低限度。您在 in 中执行的所有context操作MyHolder都可以转换为使用getView()Adapter 中保存的 Context 引用执行的操作。这将是设计使然,因为肯定不需要您的设计需要的多个上下文引用。

于 2014-09-02T04:50:01.950 回答