Android Studio 2.3.3。
我的布局xml文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="@+id/downloadProgressBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
在我的 app / build.gradle :
中apply plugin: 'com.android.application'
apply plugin: 'com.jakewharton.butterknife'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
applicationId "com.myproject"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
dev {
initWith(debug)
}
}
}
dependencies {
annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0'
annotationProcessor "com.jakewharton:butterknife-compiler:$BUTTER_KNIFE_VERSION"
compile "com.jakewharton:butterknife:$BUTTER_KNIFE_VERSION"
}
MyActivity的片段:
public class MyActivityextends extends AppCompatActivity {
@BindView(R.id.downloadProgressBar) ProgressBar downloadProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf_viewer_activity);
ButterKnife.bind(this);
ButterKnife.setDebug(true);
// THROW NPE!!!
downloadProgressBar.setVisibility(View.GONE);
}
}
但是在开始这项活动之后我得到了NPE:
NullPointerException at com.myproject.MyActivity.onCreate(MyActivity.java:63)
为什么呢?我想我正确初始化butterKnife lib。项目成功从Android Studio和控制台构建和运行。
答案 0 :(得分:3)
您正在使用Kotlin,所以您应该
apply plugin: 'com.android.application'
//apply plugin: 'com.jakewharton.butterknife'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
和
dependencies {
kapt 'com.github.bumptech.glide:compiler:4.2.0'
kapt "com.jakewharton:butterknife-compiler:$BUTTER_KNIFE_VERSION"
compile "com.jakewharton:butterknife:$BUTTER_KNIFE_VERSION"
}
答案 1 :(得分:0)
只需要声明变量downloadProgressBar
的类型。
@BindView(R.id.downloadProgressBar) ProgressBar downloadProgressBar;
答案 2 :(得分:0)
更改
@BindView(R.id.downloadProgressBar) downloadProgressBar;
这一行
@BindView(R.id.downloadProgressBar) ProgressBar downloadProgressBar;