Android 在ButterKnife中解除绑定视图

示例

片段的视图生命周期与活动不同。在onCreateView中绑定片段时,在onDestroyView中将视图设置为null。当您调用bind为您执行此操作时,Butter Knife会返回Unbinder实例。在适当的生命周期回调中调用其unbind方法。

一个例子:

public class MyFragment extends Fragment {
  @BindView(R.id.textView) TextView textView;
  @BindView(R.id.button) Button button;
  private Unbinder unbinder;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.my_fragment, container, false);
    unbinder = ButterKnife.bind(this, view);
    // TODO使用字段...
    return view;
  }

  @Override public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
  }
}

注意:调用不是必需的,但建议您调用unbind(),onDestroyView()因为如果您的应用程序具有较大的堆栈,它将节省大量内存。