Configuring ButterKnife in your project
suggest changeFor an application module on Android Gradle plugin 2.2 or newer, add Butter Knife and its annotation processor. You do not need the android-apt plugin. annotationProcessor is what runs butterknife-compiler. The Jack compiler uses that same configuration.
dependencies {
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}
Call ButterKnife.bind in onCreate of an activity, or in onCreateView of a fragment, or the annotations do nothing:
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(R.layout.fragment_example, 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 resources to their views.
@BindView(R2.id.user) EditText username;
@BindView(R2.id.pass) EditText password;
// Binding resources from drawable, strings, dimens, colors.
// In a library module every Butter Knife id argument uses R2, not R.
@BindString(R2.string.choose) String choose;
@BindDrawable(R2.drawable.send) Drawable send;
@BindColor(R2.color.cyan) int cyan;
@BindDimen(R2.dimen.margin) int generalMargin;
// Listeners
@OnClick(R2.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
}
}