Android ButterKnife Example

In this tutorial we’re going to discuss the Android ButterKnife tool and look into it’s usages.

Android ButterKnife

Android Butterknife is a view binding tool that uses annotations to generate boilerplate code for us. ButterKnife is developed by Jake Wharton at Square and is essentially used to save typing repetitive lines of code like findViewById(R.id.view) when dealing with views, thus making our code look a lot cleaner.

ButterKnife Android Dependency

To use ButterKnife in android application we need to add the following dependency to our build.gradle file.

Android ButterKnife inject

Before using any views, we need to inject ButterKnife by adding below code in onCreate() method of the activity.

Note: When using fragments we need to specify the source of the view in the onCreateView() as below.

Android ButterKnife Example

A simple activity example with ButterKnife is shown below.

In the above code snippet, @OnClick is the ButterKnife annotation that removes the need for the setOnClickListener method. The method below is automatically configured to that annotation. An argument inside the method is optional.

We can specify multiple IDs in a single binding for common event handling as shown below.

In the above code a specific type of view (Button) is automatically casted.

An example of implementing ButterKnife in fragments is given below.

For a ListView itemClick the following annotation is used.

Note: An exception will be raised if the target view is not found. To suppress this exception we can add a @Nullable annotation, thereby making it an optional binding.

This brings an end to ButterKnife in android short tutorial. For a complete example, please read Android Notification.

Reference: ButterKnife at GitHub

By admin

Leave a Reply

%d bloggers like this: