Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inheritance in fragments & ButterKnife #630

Closed
xdr-kzh opened this issue Jun 20, 2016 · 3 comments
Closed

Inheritance in fragments & ButterKnife #630

xdr-kzh opened this issue Jun 20, 2016 · 3 comments

Comments

@xdr-kzh
Copy link

xdr-kzh commented Jun 20, 2016

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?

@jaredsburrows
Copy link
Contributor

jaredsburrows commented Jun 26, 2016

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

@GuyDavis90
Copy link

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).

@JakeWharton
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants