Android Butterknife - 在碎片中进行绑定

51

我第一次使用Butterknife,但是似乎有些问题。我有一个片段、一个Listview和一个TextView只是为了测试,但是Butterknife不会绑定我的变量:

public class MyFragment extends Fragment {

    @Bind(R.id.resultListView) ListView resultList;

    @Bind(R.id.textView1) TextView test;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        ButterKnife.bind(this, view);
        System.out.println(resultList); //null
        System.out.println(view.findViewById(R.id.resultListView)); //works
        System.out.println(test); //null
        System.out.println(view.findViewById(R.id.textView1)); //works
        return view;
    }

}

没有任何异常或错误。手动绑定可以正常工作,所以我的视图必须存在。


你的依赖关系是什么样子的? - kandroidj
我只是包含了Butterknife的jar文件。 - breakline
啊,那你是在使用 Eclipse 吗? - kandroidj
是的,不幸的是这个项目还没有更新。 - breakline
3个回答

62

这对我起作用:

Gradle

compile 'com.jakewharton:butterknife:8.6.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'

代码

.
...

@BindView(R.id.text_input)
TextView text_input;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    ButterKnife.bind(this, view);
    return view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    text_input.setText("Lorem Ipsum");
...
.

我从另一个项目中复制了compile 'com.jakewharton:butterknife:8.6.0',但是错过了annoationProcesser。一旦我添加了这行并重新同步了项目,它就像魔法般地运行了。谢谢。 - John Pang

24

完成时不要忘记发布:

 private Unbinder unbinder;

...

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.finalisation_step_fragment, container, false);
        unbinder = ButterKnife.bind(this, v);
        //initialize your UI

        return v;
    }

...

   @Override public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

6
我從未這樣做過 - 這是否專門需要用於片段? - Someone Somewhere
2
是的,这是专门针对片段需要的,因为它具有不同的生命周期。这在文档中有提到。 - wseme

19

谢谢,已经完成了,但有趣的是生成的文件夹是空的。我没有注意到,但我猜这可能与此有关? - breakline
如果你进行一次干净的构建会怎样? - Dan Lew
一样的。我假设注解处理器从未被调用? - breakline
听起来是这样的 - 或许这个链接会有所帮助?https://dev59.com/zH_aa4cB1Zd3GeqP1UoQ#26036146 - Dan Lew
谢谢,我的项目之前看起来就像那样,但是在完全重新启动Eclipse后它现在可以工作了。我猜Clean/Rebuild不够哈哈。重新启动Eclipse后,它实际上生成了文件。 - breakline

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接