Where should I unbind ButterKnife 8.x.x in a ViewHolder?

Balázs Árva picture Balázs Árva · Jun 24, 2016 · Viewed 9.2k times · Source

I have a RecycleView.ViewHolder class which use ButterKnife annotations.

Should my code unbind() in this ViewHolder class too?

public class AView extends RecyclerView.ViewHolder
{
    @BindView(R.id.a_text_view) TextView aText;

    public AView(final View view)
    {
        super(view);
        ButterKnife.bind(this, view); // It returns an Unbinder, but where should I call its unbind()?
    }
}

The docs (http://jakewharton.github.io/butterknife/) does not talk about this issue.

Answer

Tim Malseed picture Tim Malseed · Apr 27, 2017

According to Jake Wharton, author of Butterknife, unbind() is only required for Fragments. See this comment on the issue tracker:

https://github.com/JakeWharton/butterknife/issues/879

Q: In the RecyclerView, how do we unbind the ViewHolder?

A: You don't need to. Only Fragments need to in onDestroyView().

The reason being that

[ViewHolders] don't outlive the associated view. A Fragment does.

In other words, because a Fragment may continue to exist after its Views are destroyed, you need to call .unbind() from a Fragment to release the reference to the Views (and allow the associated memory to be reclaimed).

With a ViewHolder, the lifecycle of the holder is the same as the Views it holds. In other words, the ViewHolder and its Views are destroyed at the same time, so there's never a lingering reference from one to the other that you need to manually clear.