Butterknife custom view unbind

[亡魂溺海] 提交于 2020-01-13 08:07:35

问题


What's the best practice for calling : -

Butterknife.unbind()

in a custom Android view please?


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/36794872/butterknife-custom-view-unbind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!