问题
I am using Butterknife to bind a single view in one of my fragments. I have used Butterknife with no issue in a separate fragment, but for some reason in this fragment the bound view is null. I am trying to add a child layout to it and I am receiving a NPE and I cannot figure out why. The setup I have in this fragment is the same as I have in my other fragment that works perfectly.
This is a snippet from the fragment including the Butterknife code.
private View view;
@BindView(R.id.layoutHolder)
LinearLayout layoutHolder;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_log, container, false);
ButterKnife.setDebug(true);
ButterKnife.bind(this, view);
return view;
}
This is the method that is throwing the NPE.
private void addLayoutToHolder(LinearLayout layout) {
layoutHolder.addView(layout, 0);
}
Here is the error:
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.LinearLayout.addView(android.view.View, int)'
on a null object reference
at com.omitted.LogFragment.addLayoutToHolder(LogFragment.java:101)
Here is the output from Butterknife.setdebug, which seems to be fine.
Looking up view binder for com.omitted.LogFragment
HIT: Loaded view binder class.
Looking up view binder for com.omitted.CalculatorFragment
HIT: Loaded view binder class.
I also checked to make sure that layoutHolder is indeed null, and it is. But for the life of me I cannot figure out why.
I can assign layoutHolder right before I add a layout to it, and it works just fine.
private void addLayoutToHolder(LinearLayout layout) {
layoutHolder = ButterKnife.findById(view, R.id.layoutHolder);
layoutHolder.addView(layout, 0);
}
So it works for now, but I do not understand why in the hell Butterknife.bind in my onCreateView is not binding the view correctly.
I hope I described this problem well enough...
Thanks for any insight.
回答1:
I had the same problem and I solved it adding the butterknife-compiler as apt. You can see it in the readme of ButterKnife
回答2:
Be sure that you are implementing the dependency like this
dependencies {
/* ... */
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}
The annotationProcessor line is very important
回答3:
My guess is that you are calling addLayoutToHolder before the ButterKnife binding has taken place, that's why layoutHolder is null. At what point of the lifecycle are you calling that method?
回答4:
I found that after enabling the jack compiler options in the gradle with
...
jackOptions.enabled = true
...
somewhere butterknife fails to find the view binder and views are always null.
来源:https://stackoverflow.com/questions/38580825/bound-view-is-null-when-using-butterknife-in-fragment