@BindView问题 Attempt to invoke virtual method 'void android ...' on a null object reference

Caused by:java.lang.NullPointerException:

Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setNavigationIcon(int)' on a null object reference

我这边是问题主要是
ButterKnife 版本更新问题, 8.0.0之前的Bind标签在8.0.0之后变成了BindView,
我们直接把@Bind改为@BindView,编译没问题,可是运行就会报空指针。

问题复现:添加8.0以后的ButterKnife库出现,绑定VIEW出现空指针问题

如:

解决方法:

第一步:在自己的工程Project文件  build.gradle 中添加依赖路径

  classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'

如:

第二步:在module模块(如 app)文件  build.gradle 中 添加依赖的  Butterknife jar

    implementation 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'

如:

 

第三步:安装ButterKnife 组件,

打开 File -> Setting -> plugins  ,搜索ButterKnife , 安装 android ButterKnife Zelezny

如:

最后编译,运行就Ok了。

关于butterknife使用,注意事项:


    1、在Activity 类中绑定 :ButterKnife.bind(this);必须在setContentView();之后绑定;且父类bind绑定后,子类不需要再bind。

    2、在非Activity 类(eg:Fragment、ViewHold)中绑定: ButterKnife.bind(this,view);这里的this不能替换成getActivity()。

    3、在Activity中不需要做解绑操作,在Fragment 中必须在onDestroyView()中做解绑操作。
    
    4、使用ButterKnife修饰的方法和控件,不能用private or static 修饰,否则会报错。错误: @BindView fields must not be private or static. (com.zyj.wifi.ButterknifeActivity.button1)

    5、setContentView()不能通过注解实现。(其他的有些注解框架可以)

    6、使用Activity为根视图绑定任意对象时,如果你使用类似MVC的设计模式你可以在Activity 调用ButterKnife.bind(this, activity),来绑定Controller。

    7、使用ButterKnife.bind(this,view)绑定一个view的子节点字段。如果你在子View的布局里或者自定义view的构造方法里 使用了inflate,你可以立刻调用此方法。或者,从XML inflate来的自定义view类型可以在onFinishInflate回调方法中使用它。

总结:多动手,独立思考

欢迎加入我的Java与Android逆向开发交流QQ群,交流学习。

猜你喜欢

转载自blog.csdn.net/ly_xiamu/article/details/83653896