I have a question about Fragment inheritance. For example, I have an BaseFragment with some binded views. Also, I have an ExtendedBaseFragment, which also has his own binded views. It is correct to unbind only in parent class (BaseFragment) or not? In this situation, in onDestroyView() unbinder is already is null. Why?
If you make a protected Unbinder mUnbinder object in your BaseFragment and then subclass it MyFragment, you need to make sure that your are setting mUnbinder = ButterKnife.bind(this, view); in your onCreateView.
Here is an example:
class BaseFragment {
protected Unbinder mUnbinder;
@Override
public void onDestroyView() {
if (this.mUnbinder != null) {
this.mUnbinder.unbind();
}
super.onDestroyView();
}
}
Then in your subclass:
class MyFragment {
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View view = inflater.inflate(R.layout.fragment_page, container, false);
this.mUnbinder = ButterKnife.bind(this, view);
return view;
}
}
Can't they both go into the superclass?
My understanding was that it would still call the subclass unbind through the magic of reflection.
I'm still using an older version of ButterKnife in my current project but it seems to be calling the subclasses unbind functions (not using an Unbinder, but rather using the ButterKnife.unbind function).
You only need to hold the unbinder in the base fragment. Not in any of the subclasses. Reflection looks up the most specific view binder thus the returned unbinder will unbind the entirety of the views in the type hierarchy.
Most helpful comment
If you make a
protected Unbinder mUnbinderobject in yourBaseFragmentand then subclass itMyFragment, you need to make sure that your are settingmUnbinder = ButterKnife.bind(this, view);in youronCreateView.Here is an example:
Then in your subclass: