Configure your project-level build.gradle
to include the android-apt
plugin:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
}
}
Then, apply the android-apt
plugin in your module-level build.gradle
and add the ButterKnife dependencies:
apply plugin: 'android-apt'
android {
...
}
dependencies {
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}
Note: If you are using the new Jack compiler with version 2.2.0 or newer you do not need the android-apt
plugin and can instead replace apt with annotationProcessor
when declaring the compiler dependency.
In order to use ButterKnife annotations you shouldn't forget about binding them in onCreate()
of your Activities or onCreateView()
of your Fragments:
class ExampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Binding annotations
ButterKnife.bind(this);
// ...
}
}
// Or
class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(getContentView(), container, false);
// Binding annotations
ButterKnife.bind(this, view);
// ...
return view;
}
}
Snapshots of the development version are available in Sonatype's snapshots repository.
Below are the additional steps you'd have to take to use ButterKnife in a library project
To use ButterKnife in a library project, add the plugin to your project-level build.gradle
:
buildscript {
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
}
}
…and then apply to your module by adding these lines on the top of your library-level build.gradle
:
apply plugin: 'com.android.library'
// ...
apply plugin: 'com.jakewharton.butterknife'
Now make sure you use R2
instead of R
inside all ButterKnife annotations.
class ExampleActivity extends Activity {
// Bind xml resource to their View
@BindView(R2.id.user) EditText username;
@BindView(R2.id.pass) EditText password;
// Binding resources from drawable,strings,dimens,colors
@BindString(R.string.choose) String choose;
@BindDrawable(R.drawable.send) Drawable send;
@BindColor(R.color.cyan) int cyan;
@BindDimen(R.dimen.margin) Float generalMargin;
// Listeners
@OnClick(R.id.submit)
public void submit(View view) {
// TODO submit data to server...
}
// bind with butterknife in onCreate
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// TODO continue
}
}