Butterknife: How to @BindView a parent view from a fragment ?

Created on 15 May 2016  路  3Comments  路  Source: JakeWharton/butterknife

I am kinda new to android development.
I am not sure how to @BindView a view that belongs to the parent view ,

To simply explain I have a Parent view and it has fragment , I want to get the FloatingActionButton which is in the parent view from my fragment class.

Usual @BindView(R.id.fab) FloatingActionButton fab, from my fragment throw NullPointerException.

I tried to ButterKnife.bind(getActivity()) from my onActivityCreated , instead ButterKnife.bind(this, rootView) from my onCreateView of the fragment ,
I thought It might work because it will load every view from the activity and not just the fragment view but it didn't.

I tried to search for this but I couldn't find any good solution.

Most helpful comment

This is generally poor practice. Bind the FAB in the activity and use some other mechanism to inform the fragment it was clicked (like from a listener between the fragment to the activity).

There's no support in Butter Knife for this (beyond passing the activity view as the root) and we are not looking to add it.

All 3 comments

You can't or probably you should not.
Instead use @BindView for fab in your Activity.

and then create helper methods for performing various actions on fab
for e.g -

public void setFabClickListener(OnClickListener listener) { fab.setOnClickListener(listener); }

and then in your Fragment

((MainActivity)getActivity()).setFabClickListener(new OnClickListener(){ @Override public void onClick(View v){ //TODO perform some action } });

This is generally poor practice. Bind the FAB in the activity and use some other mechanism to inform the fragment it was clicked (like from a listener between the fragment to the activity).

There's no support in Butter Knife for this (beyond passing the activity view as the root) and we are not looking to add it.

An easier solution is to just use findViewById in the fragment for that particular view. It's one line of code.

Was this page helpful?
0 / 5 - 0 ratings