Butter Knife: A Must-Have Library for Any Project

Butter Knife is a view binding library that almost every Android developer adds to their projects as the first thing nowadays. What Butter Knife does is simple: It basically binds views created in XML layout files to fields and methods in Java classes using annotations.

Let me show how Butter Knife works with an example. First, you need to add the following dependencies to your module-level “build.gradle” file:

Our Activity has the following XML layout set as its content view:

In our Activity class, to be able to use these views, Butter Knife helps us as follows:

Here, I implemented two most commonly used annotations provided by Butter Knife library. First one is  @BindView. We use this annotation to bind fields to the views defined in XML layout file. After setting the content view of our Activity as the XML layout shown above, we also need to call  ButterKnife.bind(this) to complete the binding. After this call, we are free to use the views anywhere inside our class.

I also implemented the  @OnClick annotation to show you how easily we can set an on-click listener for the button. Through this annotation, each click on the button is caught by the  onButtonClicked() method.

There’s more to learn regarding Butter Knife. See here to find out all: http://jakewharton.github.io/butterknife. Thanks to Jake Wharton, we can now say goodbye to  findViewById()s and many other code lines that exist just for being garbage.

Leave a Reply

Your email address will not be published. Required fields are marked *