Android Working with ButterKnife ViewBinding Library

ButterKnife is an Android library for view injection, that injects views into android activities or fragments using annotations.

One quick example; If we use @BindView annotation it helps avoid writing findViewById() method within our code. It’s because the @BindView annotation automatically typecasts the view element.

Butterknife does not simply provide view binding alone, it also provides a lot of other options like String binding, dimens binding, drawables binding, click events binding, and many more.

 

1. Basic Setup

First thing to do is to add ButterKnife library to your project by adding the below dependencies in your project level build.gradle file.

After adding these to the file, simply sync your project and continue with next step.

 

2. The working in a basic Activity class file

After adding the dependencies to the gradle, all the annotations will become available to import. We will see how @BindView and @OnClick annotations can be used.

For example, Let us consider we have the below layout having a TextView, an EditText and a Button.

 

To make the views available in the activity, we need to follow the below steps.

1. call @BindView along with the id of the view while declaring the view variable.

@BindView(R.id.text_title)

2. After calling setContentView() method, Call ButterKnife.bind(this).

 

Thus the class file will finally look like,

 

3. Within Fragments

Butterknife in fragments is the same as in an Activity, with an exception that the ButterKnife.bind() method usage is different. In a fragment, the inflated view will be passed as param along with the target parameter. Since the life cycle methods are little different in fragments, you should use the Unbinder to unbind the view within onDestroyView() method.

Carefully look down the below example:

 

4. Within Resources ( Strings, Colors, Dimens, Drawables etc,. )

Butterknife not just allows binding of views, but also bind other resources like strings, colors, dimens, and drawables.

Below example demonstrates the usages of multiple annotations

 

Conclusion

Not only ButterKnife allows binding views, but also it provides a lot of other binding options such as binding Click Listener and list Adapters too. It reduces the boilerplate of common patterns and simplifies the code and makes it more human readable.

Leave a Reply

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