简体   繁体   English

ButterKnife 不绑定视图并导致异常

[英]ButterKnife is not binding views and causing exceptions

I am using Butterknife(10.2.1) to bind views in a project.I recently migrated it to AndroidX.我正在使用 Butterknife(10.2.1) 绑定项目中的视图。我最近将它迁移到 AndroidX。

Though I am doing everything according to documentation here By calling虽然我是根据这里的文档做的一切通过调用

@BindView(R.id.layout_purchase_item1)
View layoutPurchaseItem1;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_purchase);
  ButterKnife.bind(this);
  layoutPurchaseItem1.setOnClickListener(this);

It is not working and giving me below exceptions:它不工作,并给我以下例外:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.sdf.bp.billings.PurchaseActivity.onCreate(PurchaseActivity.java:108)

It is clear that the views are not binding here but I did nothing wrong in the layout file as just replacing binding with findViewById takes care of the exception.很明显,这里的视图没有绑定,但我在布局文件中没有做错任何事情,因为只是用findViewById替换绑定会处理异常。 But I want to use Butterknife.但我想用黄油刀。 Any ideas?有任何想法吗?

Can you please update your build.gradle with below dependencies.您能否使用以下依赖项更新您的 build.gradle。

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

After updating inject the view with butterknife.更新后用黄油刀注入视图。

Add following lines in gradle file under buildTypes tag在 buildTypes 标签下的 gradle 文件中添加以下行

   ` lintOptions {
    disable 'RestrictedApi'
}
compileOptions {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}

and in my project gradle file并在我的项目 gradle 文件中

classpath 'com.android.tools.build:gradle:3.4.2'

It is working in my case in same 10.2.1 version with androidX它在我的情况下在与 androidX 相同的 10.2.1 版本中工作

I have applied kapt 'com.jakewharton:butterknife-compiler:10.2.1' before.我之前应用过kapt 'com.jakewharton:butterknife-compiler:10.2.1' I tried to clean up cache of Android Studio by Invalidate Cache and Restart but it did not work too.我试图通过无效缓存和重启来清理 Android Studio 的缓存,但它也不起作用。 I deleted .gradle and .idea today and after re syncing the project the issue was fixed.我今天删除了 .gradle 和 .idea,重新同步项目后,问题得到解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM