aprofromindia
aprofromindia

Reputation: 1129

Butterknife custom view unbind

What's the best practice for calling : -

Butterknife.unbind()

in a custom Android view please?

Upvotes: 11

Views: 5505

Answers (4)

PKDev
PKDev

Reputation: 21

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.

Upvotes: 1

CoolMind
CoolMind

Reputation: 28773

Warning!

If you set attributes with app:attribute="value" in XML, you will lose their values when reading with:

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

    TypedValue typedValue = new TypedValue();
    TypedArray typedArray = getContext().obtainStyledAttributes(typedValue.data, R.styleable.YourStyleable);
    try {
        int number = typedArray.getResourceId(R.styleable.YourStyleable_number, 0);
        image.setImageResource(number);

        String text = typedArray.getString(R.styleable.YourStyleable_text);
        text.setText(text);
    } finally {
        typedArray.recycle();
    }
}

Their values will be 0 and null. Initialize them in custom view's constructor.

A reason is using obtainStyledAttributes(typedValue.data instead of obtainStyledAttributes(attrs.

See: Magic with obtainStyledAttributes method.

Upvotes: 0

N J
N J

Reputation: 27505

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()
}

Upvotes: 10

Wahib Ul Haq
Wahib Ul Haq

Reputation: 4385

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();
}

Upvotes: 26

Related Questions