Sachit Wadhawan

Butter Knife (Binding/Injecting View, Methods in Android)

logo
Butter Knife

Dealing with redundant code sometimes becomes frustrating and unattractive for developers now a days. To overcome this problem we have a great library that can deal with the redundancy of code called “Butter Knife”.

Butter Knife is a light weight injection library that can help Android Developers to write clean code in a minimal time. This library is developed by Jack Wharton, and is hosted on Github at https://github.com/JakeWharton/butterknife. It allows developers to perform injections or bindings on arbitrary objects, views, listeners. It provides @Bind() method in place of findViewById() and @OnClick() in place of various listeners, now developers can only focus on writing useful code. Butter Knife surely reduced development time. I have found it to be very easy to use and understand.

Here are some reasons why you should use Butter Knife while working.

    1. Get Rid of findViewById
      You all are familiar with the below mentioned piece of code
      TextView lName = (TextView)findViewById(R.id.name);
      ImageView lImage = (ImageView)findViewById(R.id.image);

      Butter Knife does this work very quickly. For example:
      @Bind(R.id.name)
      public TextView lName;
      @Bind(R.id.image)
      public ImageView lImage;
    2. Better and easy way to write listeners
      The old way for writing OnClickListeners can be easily achieved by writing just a minor piece of code. For example:

      Earlier way of writing listeners:
      button.setOnClickListener(new View.OnClickListener(){
      @Override
      public void onClick(View v) {
      doSomething()
      }}); }

      Butter Knife provides easy way to achieve this
      @OnClick(R.id.buttonId)
      public void doSomething() {
      // Do stuff
      }

    3. Eliminate resource lookups by using resource annotations on fields.
      With the help of Butter Knife you can bind pre-define resources with @BindBool, @BindColor, @BindDimen, @BindDrawable, @BindInt, @BindString which binds R.bool Id to its corresponding field. For Example:
      @BindString(R.string.name) String name;
      @BIndColor(R.color.green) int green;

Setting up this library is really simple, just add this dependency to your build.gradle, and you’re good to go:

compile ‘com.jakewharton:butterknife:7.0.1’

For more documentation, please visit its website at:

http://jakewharton.github.io/butterknife/

References: 
  1. Github repo – https://github.com/JakeWharton/butterknife
  2. The Butterknife logo has also been taken from Butterknife’s website.