Working with ButterKnife in Android

logo

The following tutorial will help you understand Butter Knife implementation in Android

Why to use Butter Knife for Android?

Butter Knife in short is used in case for method binding of Android Views. Butter Knife is mainly used to make coding clean and simple especially in cases where where you deal with complex layout. Usually if you aren’t using Butter Knife you’ll have to eventually use findViewById() method for each view that you create in your layout, in cases where your application deals with many TextView’s, EditText’s, Button’s , ImageView’s the lines of code you write extends. In such cases Butter Knife comes in handy, using which you can reduce many lines of code and simply avoid methods such as findViewById().

Does Butter Knife make your App to slow down ?

No. Butter Knife doesn’t slow down your App, it gives the same result as when you declare your views using findViewById. The reason behind it is ButterKnife automatically generates findViewById calls at compile time itself thus, making use of “Annotation Processing”.

Butter Knife in Action :

Usage in xml :

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="15dp"
android:id="@+id/butterknifeLayout"
android:layout_marginLeft="@dimen/pager_margin"
android:layout_marginRight="16dp"
android:weightSum="2">

<EditText
android:id="@+id/butterknifeEdittext"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="13sp"
android:hint="First Name"
android:singleLine="true"
android:layout_weight="1"/>
 
</LinearLayout>;
 

Usage in Java class.
 
@InjectView(R.id.butterknifeLayout)
LinearLayout linearLayout;
@InjectView(R.id.butterknifeText)
EditText edittext;
 
//Just use the below code for setting a OnclickListener. That’s it. you don’t need to use findViewById multiple times
 
@OnClick(R.id.butterknifeLayout)
void OnLayoutClicked(View view) {
 
//Do Your Stuff here
}

Learn more about butterknife at : http://jakewharton.github.io/butterknife/

the-dagger

Android Developer, Open Source Enthusiast

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.