1. 程式人生 > >Fragment中使用ButterKnife初始化view失敗

Fragment中使用ButterKnife初始化view失敗

之前文章裡寫的 裡提過,在Fragment中使用ButterKnife初始化view會提示空指標異常的問題,經過哥們們一起分析,是我的一個缺乏經驗的低階操作失誤。

程式碼中呼叫正常

在程式碼中按照作者的呼叫方法初始化繫結view的操作是正常的,例如:

  • In Activity
class ExampleActivity extends Activity {
  @BindView(R.id.title) TextView title;
  @BindView(R.id.subtitle) TextView subtitle;
  @BindView(R.id.footer) TextView footer;

  @Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ButterKnife.bind(this); // TODO Use fields... } }
  • RESOURCE BINDING
class ExampleActivity extends Activity {
  @BindString(R.string.title) String title;
  @BindDrawable
(R.drawable.graphic) Drawable graphic; @BindColor(R.color.red) int red; // int or ColorStateList field @BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field // ... }
  • NON-ACTIVITY BINDING,like in Fragment
public class FancyFragment extends Fragment {
  @BindView
(R.id.button1) Button button1; @BindView(R.id.button2) Button button2; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fancy_fragment, container, false); ButterKnife.bind(this, view); // TODO Use fields... return view; } }

Gradle 依賴庫和外掛配置

重點在這裡!

在 Gradle 配置中新增 ButterKnife 的依賴庫

compile 'com.jakewharton:butterknife:8.4.0'

apt 'com.jakewharton:butterknife-compiler:8.4.0'

或者在 Project Structure -> Dependency 中新增 Library dependency ,輸入

om.jakewharton:butterknife:8.4.0,需要選擇兩個:

com.jakewharton:butterknife:8.4.0

com.jakewharton:butterknife-compiler:8.4.0

按照作者的介紹,是在 Gradle 的配置檔案中增加如下兩行:

compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'

和通過IDE新增的結果不太一致,相差在 compile&apt 手動查了下,最後確定如下流程:

  • In your project-level build.gradle file:
buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
  }
}
  • In your module-level build.gradle file:
apply plugin: 'android-apt'

android {
  ...
}

dependencies {
   compile 'com.jakewharton:butterknife:8.4.0'
   apt 'com.jakewharton:butterknife-compiler:8.4.0'
}
  • modify module-level build.gradle file
apply plugin: 'com.android.application'
apply plugin: 'android-apt'

最後整體sync一下就可以了

附記

compile與apt區別:是compile會編譯到最後的APK或library,apt不會;

  1. apt允許配置只在編譯時作為註解處理器的依賴,而不新增到最後的APK或library
  2. 設定源路徑,使註解處理器生成的程式碼能被Android Studio正確的引用

牢記!!!

完全對照官網說明寫!省的浪費時間!
2016-11-05附記:版本更新後,直接按照作者github的readme檔案內提示進行操作即可