gpt4 book ai didi

android - 在 ViewHolder 中引用 Activity

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:23 25 4
gpt4 key购买 nike

在使用 setTag 方法存储的 ViewHolder 中保留 Activity 的句柄是否安全?

我发现这个问题声称存储对 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;
}

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

我见过的所有示例代码都没有存储对持有者中 View 以外的任何内容的引用。我想知道这是巧合还是故意为之。

最佳答案

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

关于android - 在 ViewHolder 中引用 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25615489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com