在片段中使用Butterknife时绑定视图为null [英] Bound view is null when using Butterknife in fragment

查看:696
本文介绍了在片段中使用Butterknife时绑定视图为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Butterknife在我的一个片段中绑定一个视图.我在一个单独的片段中使用Butterknife时没有任何问题,但是由于某些原因,在该片段中绑定视图为null.我正在尝试为其添加子布局,并且正在接收NPE,但我不知道为什么.这个片段中的设置与其他片段中的设置完全相同.

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.

这是片段的片段,其中包括Butterknife代码.

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

这是抛出NPE的方法.

This is the method that is throwing the NPE.

private void addLayoutToHolder(LinearLayout layout) {
    layoutHolder.addView(layout, 0);
}

这是错误:

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)

这是Butterknife.setdebug的输出,这似乎很好.

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.  

我还检查以确保layoutHolder确实为null,并且确实为null.但是对于我的一生,我不知道为什么.

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.

我可以在添加布局之前立即分配layoutHolder,它可以正常工作.

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

所以它现在可以使用,但是我不明白为什么在我的onCreateView中Butterknife.bind不能正确绑定视图.

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

感谢您的见解.

推荐答案

我遇到了同样的问题,并通过添加butterknife-compiler解决了它. 您可以在ButterKnife的自述文件中查看

I had the same problem and I solved it adding the butterknife-compiler as apt. You can see it in the readme of ButterKnife

这篇关于在片段中使用Butterknife时绑定视图为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆