Implementation of Butter knife in Android

Posted By : Arun Kumar | 31-Jul-2019

Overview:

Butter Knife is the small lightweight library with a view binding and it removes boilerplate of code for developer. It is used to get Id for binding the Views in android studio and reduce the complex code of findviewbyID in the android studio.

 

Add ButterKnife to your Gradle build configuration: 

 

Adding the following dependencies in the Build.Gradle(module app)

1). implementation 'com.jakewharton:butterknife:10.0.0'

2). annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'

 

Butter Knife requires java 8, so add the given lines of code,

android {
 compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
    }
}

 

Adding the ButterKnife zelenzy  plugin in the android studio:

 

In the android studio, go to the File > Settings > Plugins and search for butterknife zelenzy and add that plugin and restart android studio.

 

 

Uses of ButterKnife zelenzy  plugin:

After creating a layout in XML when we want to get id's of views by butterknife then just click on our layout in R.layout.our_layout and press ALT + Insert. And select those views which we want to get id's (shows in the given example).

Example:  

 

Perform onClick event in the ButterKnife:

The goal of this library is to help developers write better code, and it does so by trying to reduce the code used in onCreate method on an Activity and in onCreateView on Fragments. All we need to write in these methods in the following:

 

In Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //...
    ButterKnife.bind(this);
    //...
}

In Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_blank, container, false);
    ButterKnife.bind(this, view);
    return view;
}

 

Event Listeners in ButterKnife:

Butter Knife also makes setting event listeners of Android layout Views easy and removes the listener's implementation from the key onCreate and onCreateViewmethods.

Here’s an example:

@OnClick(R.id.button)
public void ButtonClick() {
    //Perform some action
}

 

Conclusion:

Android ButterKnife helps you create cleaner and tidier code, handling a lot of the ugly boilerplate code that android has become infamous for.

 

Request for Proposal

Name is required

Comment is required

Sending message..