Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ButterKnife 8.1.0 的配置與使用,解決空指針問題

編輯:關於 Android 開發

ButterKnife 8.1.0 的配置與使用,解決空指針問題


ButterKnife 是這兩年比較流行的開源庫,是一個 View 注入框架,主要功能是代替 findViewById() 方法。同時它還能快速綁定監聽事件,更容易實現 MVVM 模式,是非常實用的工具之一。

剛開始使用 ButterKnife 時,很多人可能會遇到 NullPointerException 或「找不到符號」的問題,這都是因為 ButterKnife 配置有誤所致。下面我們詳細說明 ButterKnife 的配置流程。

首先我們需要引入 ButterKnife 的依賴,如下圖:

同時還需要安裝 ButterKnife 的插件:

這裡我已經安裝好了,看起來會有一些不同。沒安裝時,先搜索再點下面的按鈕就會出現。

然後進行配置:

注意,這裡如果沒有完成上面安裝插件的步驟,會無法識別 apt()。

以下貼出完整的 build.gradle 供參考。首先是專案層級的 build.gradle:

 1 // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 3 buildscript { 4 repositories { 5 jcenter() 6 } 7 dependencies { 8 classpath 'com.android.tools.build:gradle:2.1.0' 9 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' 10 // NOTE: Do not place your application dependencies here; they belong 11 // in the individual module build.gradle files 12 } 13 } 14 15 allprojects { 16 repositories { 17 jcenter() 18 } 19 } 20 21 task clean(type: Delete) { 22 delete rootProject.buildDir 23 }

接著是 module 層級的 build.gradle:

 1 apply plugin: 'com.android.application' 2 3 android { 4 compileSdkVersion 23 5 buildToolsVersion "23.0.3" 6 7 defaultConfig { 8 applicationId "com.lcc.fjnu.damuvideobysohu" 9 minSdkVersion 14 10 targetSdkVersion 23 11 versionCode 1 12 versionName "1.0" 13 } 14 buildTypes { 15 release { 16 minifyEnabled false 17 proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 } 19 } 20 } 21 22 buildscript { 23 repositories { 24 mavenCentral() 25 } 26 dependencies { 27 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' 28 } 29 } 30 31 apply plugin: 'com.neenbedankt.android-apt' 32 33 dependencies { 34 compile fileTree(include: ['*.jar'], dir: 'libs') 35 testCompile 'junit:junit:4.12' 36 compile 'com.android.support:appcompat-v7:23.3.0' 37 compile 'com.android.support:design:23.3.0' 38 compile 'com.jakewharton:butterknife:8.1.0' 39 apt 'com.jakewharton:butterknife-compiler:8.1.0' 40 }

以上就是配置的過程。另外要提醒的是,ButterKnife 8.1.0 的綁定方法是 @BindView,之前的版本是 @Bind,再之前是 @InjectView。

具體說明可以參照其官網 https://jakewharton.github.io/butterknife/。這裡給出一個簡單的範例:

 1 public class MainActivity extends AppCompatActivity { 2 3 @BindView(R.id.toolbar) 4 Toolbar mToolbar; 5 @BindView(R.id.tabs) 6 TabLayout mtabs; 7 @BindView(R.id.appbar) 8 AppBarLayout mappbar; 9 @BindView(R.id.container) 10 ViewPager container; 11 @BindView(R.id.fab) 12 FloatingActionButton fab; 13 ......}

使用 ButterKnife 後,不需要重新實例化以及 findViewById(),程式碼變得更簡潔明瞭。此外,別忘了在 onCreate 中呼叫 ButterKnife.bind(this),否則就會出現空指針問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved