ButterKnife — A viewbinding library for Android (Beginner guide)

(Image credit: ButterKnife Logo)

In this post

In this post, we will detailed look into ButterKnife viewbinding library for android. Also demonstrate how it’s work, how to integrate and use in your android app development to make your development faster.

Let’s get started!

What is it?

ButterKnife is a view binding library that uses annotation to generate boilerplate code for us.It has been developed by Jake Wharton. It makes your code less and more clear. It is time saving to write repetitive lines of code.

To avoid writing repetitive code just like `findViewById(R.id.yourview)`, butterknife helps you to binds fields, method and views for you.

How to install?

It is easy to use butterknife in your project. Just follow below simple steps to install butterknife in your project.

Step 1: Add below dependency in your app level build.gradle file:

def BUTTER_KNIFE_VERSION="8.5.1" //current version of butterknife
dependencies {
compile "com.jakewharton:butterknife:$BUTTER_KNIFE_VERSION"
annotationProcessor "com.jakewharton:butterknife-compiler:$BUTTER_KNIFE_VERSION"
}

Step 2: Add below buildscript in your project level build.gradle file:

buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath ‘com.jakewharton:butterknife-gradle-plugin:8.5.1’
}
}

Step 3: Then apply plugin in your app level build.gradle using below lines:

apply plugin: ‘com.jakewharton.butterknife’

Then sync your gradle to download and install butterknife.

Great going! Now your are ready to use awesome tools.

How to Use?

1. Bind

Bind butterknife with your fragment or activity.

  • For Activity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ButterKnife.bind(this); // bind butterknife after setContectView(..)
//Now you can access all view after bind your activity with butterknife
}
  • For Fragment:
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.fragment_somelayout, container, false);
ButterKnife.bind(getActivity(), rootView);
//need to specify sources of view
return rootView;
}

2. Usage

  • Simple usage:
class MainActivity extends Activity {
// View Binding
@BindView(R.id.username) EditText edtUsername;
@BindView(R.id.button) Button btnSubmit;
// Resource binding
@BindString(R.string.str_no_internet) String noInternetMessage;
@BindColor(R.color.colorname) int bluecolor; // Specify int value or ColorStateList field
@BindDimen(R.dimen.dimem_float_value) Float floatDimen;
@BindDrawable(R.drawable.drawable_button_rounded) Drawable     
drawableButtonRounded;
}
  • Bind Multiple view into list (Example):
@Bind({R.id.edt_password, R.id.edt_confirm_password})
List<EditText> edtPasswords;
static final ButterKnife.Action<EditText> FOR_EMPTRY_PASSWORD= new ButterKnife.Action<EditText>() {
@Override
public void apply(EditText editText, int index) {
editText.setError(“Password should not be blank”);
}
};

static final ButterKnife.Action<EditText> FOR_PASSWORD_NOT_MATCH = new ButterKnife.Action<EditText>() {
@Override
public void apply(EditText editText, int index) {
editText.setText(“”);
editText.setError(“Both passwords don’t match”);
}
};
public boolean isPasswordEmpty() {
for(EditText password : edtPasswords)
{
if (password.getText().toString().isEmpty())
return true;
}
return false;
}
 private boolean isBothPasswordsMatch() {
return edtPasswords.get(0).getText()).toString().
equals(edtPasswords.get(1).getText().toString());
}

private checkValidPasswordDetails(){
if(isPasswordEmpty()) // check if both password empty
{
ButterKnife.applyedtPasswords, FOR_EMPTRY_PASSWORD);
}

if(!isBothPasswordsMatch()) // check if both password doesn't
match
{
ButterKnife.applyedtPasswords, FOR_PASSWORD_NOT_MATCH);
}
}
  • Bind Viewholder:
static class ViewHolder {
@BindView(R.id.item_title) TextView itemTitle;
@BindView(R.id.item_price) TextView itemPrice;
public ViewHolder(View view)
{
ButterKnife.bind(this, view);
}
public void bindValue(String title,int price)
{
itemTitle.setText(title);
itemPrice.setText(String.valueOf(price));
}
}
  • Event Binding: Instead of writing setOnClickListener method for every view, use @OnClick annotation provide click event for single or multiple view.
// Single view button click event
@OnClick(R.id.btnLogin)
public void submit(View view) {
// call login
}
// Multiple Button click event
//For Common event, we can specify multiple view as shown below:
@OnClick({ R.id.btnLogin, R.id.btnSignUp, R.id.tvForgotPassword }) // must have to include view here to get onClickEvent
public void setViewOnClickEvent(View view) {
switch(view.getId())
{
case R.id.btnLogin:break;
case R.id.btnSignUp:break;
case R.id.tvForgotPassword:break;
}
}

List of some event listener by butterknife:

Butterknife Annotation | Interface

> @OnEditorAction | OnEditorActionListener

> @OnFocusChange | View.OnFocusChangeListener

> @OnTouch | View.OnTouchListener

> @OnCheckedChange | CompoundButton.OnCheckedChangeListener

> @OnClick | butterknife.internal.DebouncingOnClickListener

> @OnItemLongClick | AdapterView.OnItemLongClickListener

> @OnItemClick | AdapterView.OnItemClickListener

> @OnLongClick | View.OnLongClickListener

DONE.

You can see that there is a lot of boilerplate code that is been reduced compared to using ButterKnife.

Thank you to Paresh Mayani for introducing me with this awesome library.

Wrap up:

I hope reading this article was useful I recommended to use butterknife tool which save development time and make the code look lot cleaner.
Thanks for reading this article. Be sure to share this article if you found it helpful. It means a lot to me. Meanwhile , would like to hear suggestions and inputs on this blog. Also, Let’s become friends on Twitter, Linkedin,Github, and Facebook and StackOverflow

Extra!

Android Studio plug-in for generating ButterKnife injections from selected layout XML.

References: