Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Butterknife custom view unbind

What's the best practice for calling : -

Butterknife.unbind()

in a custom Android view please?

like image 842
aprofromindia Avatar asked Apr 22 '16 13:04

aprofromindia


3 Answers

onDetachedFromWindow won't always work, like if the custom view is within a RecyclerView. Adding that in fact actually crashed my app. Honestly, it worked fine without unbinding it.

like image 108
PKDev Avatar answered Nov 27 '22 09:11

PKDev


Yes, onDetachedFromWindow is the right function as mentioned in NJ's answer because this is where view no longer has a surface for drawing.

But the usage is incorrectly mentioned in the answer. The right approach involves binding in onFinishInflate():

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    unbinder = ButterKnife.bind(this);
}

and unbinding in onDetachedFromWindow:

@Override
protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    // View is now detached, and about to be destroyed
    unbinder.unbind();
}
like image 36
Wahib Ul Haq Avatar answered Nov 27 '22 09:11

Wahib Ul Haq


Try in onDetachedFromWindow()

Unbinder unbinder;
unbinder = Butterknife.bind(this, root);

and in onDetachedFromWindow you need to call unbinder.unbind();

@Override
protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    // View is now detached, and about to be destroyed
   unbinder.unbind()
}
like image 42
N J Avatar answered Nov 27 '22 11:11

N J