Reputation: 226
I have some views and I want to bind it to one Fragment.
I called ButterKnife.Bind(this, view)
in onCreateView
, and it works like a charm.
But I met exception when I called ButterKnife.Bind(this, view.findViewById(R.id.view2))
.
(Surely view.findViewById(R.id.view2) != null
)
Why I can't inject multiple views to one owner via ButterKnife?
Edited: I know I can bind views from one root ViewGroup. I was just dubious about this situation. In my opinion, there isn't reason to cause exception but ButterKnife threw exception.
Upvotes: 4
Views: 3008
Reputation: 1572
It would help to know what your usecase is, but here is an example of multiple views from one layout being bound to local variables.
public class FancyFragment extends Fragment {
@Bind(R.id.button1) Button button1;
@Bind(R.id.button2) Button button2;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fancy_fragment, container, false);
ButterKnife.bind(this, view);
// Use fields here or later in the lifecycle of the fragment
return view;
}
}
If you have two ViewGroups as roots then it would be interesting to see what the results would be. You could add @nullable
to each @Bind
to make it an optional field and then call ButterKnife.Bind(this, view2)
after the above bind call. I don't know if that would null out the unfound views or just bind the new views.
Upvotes: 1
Reputation: 59
I think that maybe you are trying to call ButterKnife.Bind() on two child View, not the root ViewGroup.
According to the introductions, you should bind any child view to a field by declaring the field with a @Bind annotation, but not by calling ButterKnife.Bind() for each child view.
The ButterKnife.Bind() should only be called on the root ViewGroup object. In this way, it defines the scope where ButterKnife will search the view IDs.
However, if you really would like to call ButterKnife.Bind() on two root ViewGroups, then it's reasonable that an Exception occurred because according to the documentation, ButterKnife has no such usage. Actually you should have each Fragment/Activity class only related to one root ViewGroup, too.
Upvotes: 1