问题:AndroidStudio 依赖 ButterKnife 出现的空指针异常
解决:ButterKnife配置
带*号为添加的代码
app/build.gradle
apply plugin: 'com.android.application'
**apply plugin: 'com.neenbedankt.android-apt'**
android {
compileSdkVersion 24
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "com.eminvoker.mvpdemo"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
**compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'**
}
build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0'
**classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'**
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
代码中使用:(xml中有一个TextView id为tx,一个Button id为btn)
@BindView(R.id.tx)
TextView tx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
tx.setText("Hello");
}
@OnClick(R.id.btn)
public void onClick() {
tx.setText("goodbye")
}
更多用法看官方文档,这里只是随便喵喵
为了方便将xml的控件绑定到Activity中,下载插件:Android ButterKnife Zelezny
安装插件后点击Activity中的xml布局文件选择生成绑定代码(吐槽小唧唧)