Using Butter Knife to bind views and more

Butter Knife is an Android view injection library that reduces unnecessary code. This library was developed by Jake Wharton. It helps you to:

  • Bind single and multiple views
  • Bind resources
  • Bind listeners

To start using Butter Knife in your Android application all you have to do is add these 2 lines inside your build.gradle file and sync your project.

Now that that’s over and done with let’s see what we can do with Butter Knife. We are going to build a simple app now to showcase this cool library. Lets use 3 TextViews and a Button inside our activity_main.xml layout:

Binding single Views

Normally, what we do to access a View from our activity is to use findViewById(int resourceId). Gladly, Butter Knife does this for us so we no longer need to worry about forgetting to initialize our views:

All we need to write is an annotation BindView(int resourceId) and Butter Knife will inject the view for us. Also, notice we have a line ButterKnife.bind(this) in our onCreate() method which is necessary in order for this to work.

Binding multiple fields

To bind multiple fields at once we use BindViews annotation. We also create a List of textviews to store multiple TextView:

Hmm, the text seems to be too small and I want to increase it without repeating myself 2 times. In onCreate we call:

Where SIZE is a ButterKnife.Setter field. We override set() method so that we can change each TextView text size:

Binding onClick listeners

Remember that button from our activity_main.xml ? How about we use Butter Knife to register clicks and show how many times the button was clicked. For this we use OnClick(int resourceId) annotation to bind our method:

Simple as that! No need to use any setOnClickListener() and also notice that our OnCreate has a lot less lines of code. Heres the full MainActivity class:

And here’s our final result:

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.