What's the best practice for calling : -
Butterknife.unbind()
in a custom Android view please?
What's the best practice for calling : -
Butterknife.unbind()
in a custom Android view please?
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();
}
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()
}
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.