Link to activity in ViewHolder
Is it possible to store a handle to an Activity in a ViewHolder that is stored using a method setTag
?
I found this issue, which claims that keeping a link to an Activity can lead to a memory leak, but it was fixed in Android 4.0: https://code.google.com/p/android/issues/detail?id=18273
Specifically, I'm wondering if it's safe to have a ViewHolder that looks something like this:
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;
}
}
using getView method in my ArrayAdapter like this:
@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;
}
(The code is a simplified version of the actual codebase, to get the point.)
None of the code examples I've seen reference anything other than the views in the holder. I'm wondering if this is by coincidence or by design.
source to share
Whether or not it is safe in this case, it is always best to maintain contextual references. Anything you do with context
in MyHolder
can be translated into operations performed in getView()
using the Context reference contained in the adapter. This would be by design, as there is no need to have multiple context references that your design will need.
source to share