1. 程式人生 > >butterknife在library中使用問題處理

butterknife在library中使用問題處理

1. 官方指南及遇到的問題

butterknife當前版本是8.4.0,已經提供了對library project的支援,github主頁的使用步驟總結一下就是:

1.To use Butter Knife in a library, add the plugin to your buildscript:

buildscript {
  repositories {
    mavenCentral()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'
  }
}

2.and then apply it in your module:

apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'

dependencies {
  compile 'com.jakewharton:butterknife:8.4.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
}

3.Now make sure you use R2 instead of R inside all Butter Knife annotations.

class ExampleActivity
extends Activity {
@BindView(R2.id.user) EditText username; @BindView(R2.id.pass) EditText password; }

但是按照這個步驟操作後並沒有效果,用@BindView的地方提示NullPointerException,用@onClick的標註的點選事件,點選後也沒有反應

2. 最終解決方案

最後發現,只需修改一下上述步驟1和2就可以了。

步驟1加上依賴注入的plugin:

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
dependencies { classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' // 新增的部分 classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0' } }

然後步驟2也修改一下:

apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'
apply plugin: 'android-apt'

dependencies {
  compile 'com.jakewharton:butterknife:8.4.0'
  apt 'com.jakewharton:butterknife-compiler:8.4.0' // 修改的地方 把annotationProcessor改為apt
}

這樣處理之後,就正常了!

而且我們可以看到,在路徑下,已經生成了對應的中間檔案:
這裡寫圖片描述