Android-Tools: Butterknife (Maven Plugin for Android Studio)

As of this posting I have been developing on the Android platform for over three years and I cannot believe that I haven’t heard of Butterknife. Butterknife is similar to a dependency injection framework, but rather than injecting an interface Butterknife will bind an XML defined view id to a corresponding Java object or lamba callback without making petty calls to findViewById().

Butterknife accomplishes this in probably the most simple way possible. Below is an example of a bare bones Android Activity that demonstrates a simple binding on two EditText variables, a String resource, and an onClick listener.

 

class ExampleActivity extends Activity {
  @Bind(R.id.user) EditText username;
  @Bind(R.id.pass) EditText password;

  @BindString(R.string.login_error)
  String loginErrorMessage;

  @OnClick(R.id.submit) void submit() {
    // TODO call server...
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // TODO Use fields...
  }
}

As you can see, with the @Bind(R.id.myID) annotation Butterknife will map this id directly to your instance variable or onClick function. No more cluttered onCreate methods, repeated id lookups, or any other processes that extend development time. If you want to cut down on wasted developer, make sure they’re using Butterknife! Their plugin can be installed from Android studio or downloaded from their Github here.
 

You may also like...