Thursday, 12 January 2017

Android Working With ButterKnife On Activity And Fragment

In this tutorial i going to share about one awesome library that help you easy manage your code (and i think you code more cleaner that before), the library called ButterKnife.

ButterKnife is a library that makes you more easy to cast your view. For example if you usually spent much time to find the id of your view (Red : findViewById(, this library will save a lot of your time. ButterKnife was developed by Jake Wharton.


In normal code, you may do like the following code :

In code above, you will work twice, why?

First, you have to define your view : private TextView tvName; It's fine if your view is not too much, but if your view is much, you have to define you view first, after that you also have to define the id inside onCreate().

If you need more efficient work, you must use this library. As i wrote above, this library save your time much.


Compile the library in your build.gradle (module : App) :

//add this line for butterknife
compile 'com.jakewharton:butterknife:7.0.1'

Define the ButteKnife inside the onCreate(), exactly below the setContentView() :


Implementation on Activity

The code below will show you how to use butterknife to make you work more efficient. Here the code of

@Bind = Use to define your view by its id. Make sure under @Bind is the view that owner of the id that has defined inside @Bind.

@OnClick = Use to the define the id that do onClickListener. In this project i use two buttons, so inside @OnClick there are an array id of the buttons.

if you just use one button (one OnClick), you don't need to use an array, just define like the following code snippet :

public void onClickButton(){
       //Your Action
Implementation on Fragment

Look at the code above, there is a different how to define ButterKnife. In fragment you have to write like this : ButterKnife.bind(this, view); . You have to include the view.

Hope the tutorial above is useful for you. Thank you.