Android ButterKnife Library For View Binding With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.
Hello Readers! In this post, we will study about android Butterknife library for view binding. We will study about how to use android butterknife library to bind or inject views in the application. This tutorial will also show various ways of using butterknife library. For example, use it to set click listener in single or multiple views, bind a single or multiple views, bind resources such as strings, dimensions, colors etc. Everything will be explained using examples so that it’s use becomes clear to you.

It would be helpful for you if you already know about Button, TextView, EditText and RecyclerView.

Android ButterKnife Library is view injection or view binding library that injects or binds views using annotations into activity or fragment in android application. For example, @BindView is used to bind view into the application. You just need to provide the id of the view to which you want to apply click listener.

Different Uses of ButterKnife Library

We can use Android butterknife library in many ways. For example, we can use
– to set onClick listener in single element,
– to set onClick listener in multiple elements,
– in Fragments to bind views,
– in Activity to bind views,
– in ListAdapter to bind views,
– to bind Resources – Strings, Color, Dimens, Drawables etc.,
– to group Multiple Views Into List and Apply same Action

In this tutorial, we will go through a sample application that will demonstrates use of android Butterknife library for view binding in different scenarios in the application. Meanwhile, you can see output of the tutorial or get sourcecode and run to see the output.

Output

Source Code

You can download source code of this tutorial on android ButterKnife Library by entering the details –



Getting Started

The tutorial consists of various scenarios in which android butterKnife library can be used.
Before using butterknife in android application, you will have to create an android application and do some basic setup.

1. Creating New Project

Follow steps below to create new project. Please ignore the steps if you have already created a new application.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as ButterKnifeTutorial. Then, click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail.

1.2 Adding ButterKnife Library Gradle

Add butterknife library gradle into app/build.gradle file in the application. So, open app/build.gradle file and add below code into it.

// Gradle For ButterKnife...
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

After adding these gradles in app/build.gradle file, click on Sync Now button. Then, wait till the build process is complete.

1.3 Modify values Folder

Add the constant values to be used in the application.

Note – If you won’t add these constants in values folder, you will get error while going through the tutorial.
Open res/values/strings.xml file. Then, add below code into it.

<resources>
	<string name="app_name">ButterKnifeTutorial</string>
	<string name="no_image">no image</string>
	<string name="message">We have used ButterKnife for resources binding</string>
	<string name="disable_views">Disable Views</string>
	<string name="enable_views">Enable Views</string>
    <string name="success_message">You have successfully used Butterknife</string>
	<string name="success_message_fragment">You have successfully used ButterKnife in Fragment</string>
	<string name="btn_clicked_butterknife">Button is clicked using ButterKnife</string>
	<string name="changed_revert">Changed to Tutorialwing, Click to Revert</string>
	<string name="click_change">Click to change</string>
	<string name="click_on_the_button_to_get_message">Click on the button to get message</string>
	<string name="show_message">Show Message</string>
	<string name="click_me">Click Me</string>
	<string name="click_to_change">Click to change</string>
	<string name="first_name">First Name</string>
	<string name="middle_name">Middle Name</string>
	<string name="last_name">Last Name</string>
	<string name="use_in_activity">Use in Activity</string>
	<string name="use_in_fragment">Use in Fragment</string>
	<string name="use_in_adapter">Use in Adapter</string>
	<string name="use_as_listener">Use as Listener</string>
	<string name="use_for_resources">Use For Resources</string>
	<string name="use_for_multiple_views">Use For Multiple Views</string>
</resources>

Open res/values/dimens.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<dimen name="icon">3dp</dimen>
    <dimen name="padding_default">10dp</dimen>
    <dimen name="padding_large">30dp</dimen>
    <dimen name="text_size_default">20sp</dimen>
    <dimen name="img_width">180dp</dimen>
    <dimen name="img_height">180dp</dimen>
    <dimen name="padding_minimum">4dp</dimen>
    <dimen name="margin_bottom">5dp</dimen>
    <dimen name="list_padding">2dp</dimen>
    <dimen name="help_margin_bottom">30dp</dimen>
    <dimen name="example_resource_padding">10dp</dimen>
    <dimen name="example_views_margin">30dp</dimen>
    <dimen name="example_views_padding">30dp</dimen>
    <dimen name="first_name_padding_top">20dp</dimen>
    <dimen name="example_listener_padding">10dp</dimen>
    <dimen name="clickme_margin_top">20dp</dimen>
    <dimen name="items_padding">20dp</dimen>
    <dimen name="item_padding">10dp</dimen>
    <dimen name="item_margin_top">5dp</dimen>
    <dimen name="item_2_padding">10dp</dimen>
    <dimen name="example_padding">10dp</dimen>
    <dimen name="example_help_padding">30dp</dimen>
</resources>

Open res/values/colors.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<color name="colorPrimary">#3F51B5</color>
	<color name="colorPrimaryDark">#303F9F</color>
	<color name="colorAccent">#FF4081</color>

	<color name="red">#ff0000</color>
    <color name="bg_list_item">#f0f0f0</color>
</resources>

Apart from these three values folder, we have not modified any other value folder.

2. Examples of android butterknife library

Now, we will see how to use android butterknife library for view binding in various ways. For example – use in fragment, activity, resources or views binding etc.

2.1 Using ButterKnife in Fragment

Fragment has different life cycle than activity. So, you need to take care of binding the butterknife with fragment and unbinding it at appropriate places. Here, we are binding butterKnife in onCreateView method. When you call ButterKnife.bind(), it returns an unbinder. Use returned unbinder to unbind in onDestroyView method.

You need to create a new fragment in the application. So,
(a) Create a new xml file, named fragment_example.xml, in res/layout folder. Now, open this file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:background="@android:color/white"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="@dimen/padding_default">

    <TextView
        android:id="@+id/help"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/help_margin_bottom"
        android:gravity="center"
        android:text="@string/click_on_the_button_to_get_message" />

    <Button
        android:id="@+id/showMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/show_message" />

</LinearLayout>

Here, we have defined textView and button. We will access these widgets in java file and perform some operations using android butterknife library.

(b) Create a new file, named ExampleFragment.java, in java/com.tutorialwing.butterknife package. Now, open this file and add below code into it.

package com.tutorialwing.butterknifetutorial;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ExampleFragment extends Fragment {

	@BindView(R.id.showMessage)
	Button showMessage;

	private Unbinder unbinder;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_example, container, false);

		unbinder = ButterKnife.bind(this, view);
		// Write code to do some operations using fields...Or write in onViewCreated method...
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		// You can also use ButterKnife to set button click listener.
		showMessage.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(getActivity(), R.string.success_message_fragment, Toast.LENGTH_LONG).show();
			}
		});
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		unbinder.unbind();
	}
}

@BindView annotation has been used to bind view with id showMessage. Here, we have also shown how to bind / unbind android Butterknife library in fragment.

Note – We will soon see how to show this fragment and check if it is working perfectly or not.



2.2 Using ButterKnife in Activity

Now, We will see how to use android butterKnife library in activity, how to bind/unbind it at appropriate place.

(a) Create a new xml file, named activity_example.xml, in res/layout folder. Now, open this file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="@dimen/example_padding">

    <TextView
        android:id="@+id/help"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/example_help_padding"
        android:gravity="center"
        android:text="@string/click_on_the_button_to_get_message" />

    <Button
        android:id="@+id/showMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/show_message" />

</LinearLayout>

Here, we have defined a textView and button. Now, we will access these widgets in java file and perform some operations on it.

(b) Create a new java file, named ExampleActivity.java, in java/com.tutorialwing.butterknife package. Then, open this file and add below code into it.

package com.tutorialwing.butterknifetutorial;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ExampleActivity extends AppCompatActivity {

    @BindView(R.id.showMessage)
    Button showMessage;

    private Unbinder unbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_example);

        unbinder = ButterKnife.bind(this);

        // Though i have used setOnClickListener method here, you can also use
        // the way ButterKnife has defined to listen to click event.
        // Note: I have used this just to show the way how you can use @BindView defined by ButterKnife.
        // There is no need to check null for any view. It will automatically throw null pointer
        // exception by ButterKnife when no view, of provided ID, is found.
        showMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ExampleActivity.this, R.string.success_message, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unbinder.unbind();
    }
}

Here, ButterKnife is being binded in onCreate method and unbinded in onDestroy method. @BindView annotation is used to bind a view with id showMessage.

(c) Now, you need to mention about this activity in AndroidManifest.xml file. So, open main/AndroidManifest.xml file. Then, add below code into it.

<activity android:name=".ExampleActivity">
</activity>

Note – To run and see whether it’s working, go to section – Setup to Run and Check Example

2.3 Setting Click Listener using ButterKnife

You can set click listener on single view or multiple views using butterknife library.

To set click listener on single view, you can do it as below –

@OnClick(R.id.clickMe)
public void showMessage() {
   Toast.makeText(this, R.string.btn_clicked_butterknife, Toast.LENGTH_LONG).show();
}

Here, we have set click listener on view having id clickMe. On view click, toast message is being shown.

To set click listener on multiple views, you can do it as below –

@OnClick({R.id.item_1, R.id.item_2, R.id.item_3, R.id.item_4, R.id.item_5})
public void showMessage(TextView textView) {
    boolean isSelected = textView.isSelected();
    textView.setSelected(!isSelected);
    textView.setText(textView.isSelected() ? getString(R.string.changed_revert) : getString(R.string.click_change));
}

Here, we have set a click listener on views having ids – item_1, item_2, item_3, item_4 and item_5. On Click of any view, it’s text is being changed.

Note – Download source code to see a complete example to set click listener. Check ExampleListenerActivity.java file to see this example.

2.4 Applying Action on Multiple Views Simultaneously

Now, we will see how to use android butterknife library to perform same action on multiple views simultaneously.

We will create a new activity, ExampleMultipleViewActivity, and it’s xml file to show this example. So,
(a) Create a new xml file, named activity_example_multiple_view.xml, in res/layout folder. Then, open this file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/example_views_margin"
    android:orientation="vertical"
    android:padding="@dimen/example_views_padding">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/disable_views" />

    <EditText
        android:id="@+id/firstName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/first_name_padding_top"
        android:hint="@string/first_name" />

    <EditText
        android:id="@+id/middleName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/middle_name" />

    <EditText
        android:id="@+id/lastName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/last_name" />

</LinearLayout>

Here, we have defined three editTexts and one button. We will set click listener on button to enable/disable all editTexts when clicked.

(b) Now, create a new java file, named ExampleMultipleViewActivity.java, in main/java/com.tutorialwing.butterknife package. Then, open this file and add below code into it.

package com.tutorialwing.butterknifetutorial;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.List;

import butterknife.BindString;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ExampleMultipleViewActivity extends AppCompatActivity {

	@BindViews({R.id.firstName, R.id.middleName, R.id.lastName})
	List<EditText> nameFields;

	@BindString(R.string.disable_views)
	String disableViews;

	@BindString(R.string.enable_views)
	String enableViews;

	boolean isEnabled = true;

	private Unbinder unbinder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_example_multiple_view);

		unbinder = ButterKnife.bind(this);
	}

	@OnClick(R.id.button)
	void onClick(Button button) {
		if (isEnabled) {
			ButterKnife.apply(nameFields, DISABLE);
			ButterKnife.apply(nameFields, View.ALPHA, 0.3f);
		} else {
			ButterKnife.apply(nameFields, ENABLED, true);
			ButterKnife.apply(nameFields, View.ALPHA, 1.0f);
		}
		isEnabled = !isEnabled;
		button.setText(isEnabled ? disableViews : enableViews);

		Toast.makeText(getApplicationContext(), "Views are " + (isEnabled ? "Enabled" : "Disabled"), Toast.LENGTH_SHORT).show();
	}

	static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {
		@Override
		public void apply(View view, int index) {
			view.setEnabled(false);
		}
	};

	static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {
		@Override
		public void set(View view, Boolean value, int index) {
			view.setEnabled(value);
		}
	};

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unbinder.unbind();
    }
}

@BindViews has been used to inject the views with given id,
@BindString has been used to bind the string resources,
@OnClick annotation has been used to set click listener on button. Notice that how we are enabling/disabling all the editTexts together on button click.

(c) Now, mention about this activity in AndroidManifest.xml file. So, open main/AndroidManifest.xml file. Then, add below code into it.

<activity android:name=".ExampleMultipleViewActivity">
</activity>



2.5 Using ButterKnife Library in Resources (Strings, colors, dimens, drawables etc.)

We can also use butterknife library to bind resources such as strings, colors, dimens, drawables etc. in any application.

Create a new activity, ExampleResourceActivity, and it’s xml file to see the use of butterknife to bind resources. So,
(a) Create a new xml file, named activity_example_resource.xml, in res/layout folder. Then, open this file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="@dimen/example_resource_padding">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/no_image" />

    <TextView
        android:id="@+id/txvMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Here, we have defined an imageView and textView. we will access these imageView and textView and set image, texts etc. using butterknife library in java file.

(b) Now, create a new java file, named ExampleResourceActivity.java, in main/java/com.tutorialwing.butterknife package. Then, open this file and add below code into it.

package com.tutorialwing.butterknifetutorial;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.BindColor;
import butterknife.BindDimen;
import butterknife.BindDrawable;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ExampleResourceActivity extends AppCompatActivity {

	@BindView(R.id.txvMessage)
	TextView textView;

	@BindView(R.id.imageView)
	ImageView imageView;

	@BindString(R.string.message)
	String title;

	@BindDrawable(R.drawable.butterknife)
	Drawable drawableImage;

	@BindColor(R.color.red)
	int textColor;

	@BindDimen(R.dimen.icon)
	int spacer;

	private Unbinder unbinder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_example_resource);

		// bind the view using butterknife
		unbinder = ButterKnife.bind(this);

		textView.setText(title);
		textView.setTextColor(textColor);
		textView.setPadding(spacer, spacer, spacer, spacer);

		imageView.setImageDrawable(drawableImage);
		imageView.setPadding(spacer, spacer, spacer, spacer);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		unbinder.unbind();
	}
}

Here, we have used different annotations in this activity. Meaning of different annotations are –

(i) @BindView annotation – This is used to bind the view with given id. In this file, BindView has been used to bind imageView and textView.
(ii) @BindString annotation – This is used to bind the string resource with given name. In this file, BindString has been used to bind string with name message.
(iii) @BindDrawable annotation – This is used to bind the drawable resource with given name. In this file, BindDrawable has been used to bind drawable resource with name butterknife. Actually this resource (butterknife) is an image which it being set in imageView.
(iv) @BindColor annotation – This is used to bind the color resource with given name. In this file, BindColor has been used to bind color resource with name red.
(v) @BindDimen annotation – This is used to bind the dimension resource with given name. In this file, BindDimen has been used to bind dimension resource with name icon.

(c) Mention about this new activity in AndroidManifest.xml file. So, open main/AndroidManifest.xml file. Then, add below code into it.

<activity android:name=".ExampleResourceActivity">
</activity>

2.6 Using ButterKnife in RecyclerView

Till now, we have seen how to use butterknife library to bind views, resources (color, dimens, strings), etc. Now, we will see how to use butterknife library in RecyclerView and ListAdapter.

To demonstrate this, we will create a new activity, ExampleAdapterActivity. Then, we will use RecyclerView with it’s adapter in it. In this example, we will show a list of animal with it’s name and image using recyclerView.

We will create –
(i) A Model class, Animal.java, to represent data model.
(ii) An Adapter class and it’s xml file to show how a single item in recyclerView would look like.
(iii) An Activity class and it’s xml file to use recyclerView in it.

So, Let’s start.

Create a new folder, named recyclerview, in main/java/com.tutorialwing.butterknife package. Now, Each java file, related to this section, will be added in this folder.

(a) Create a model class, named Animal.java, in main/java/com.tutorialwing.butterknife/recyclerview folder. Then, open this file and add below code into it.

package com.tutorialwing.butterknifetutorial.recyclerview;

public class Animal {

	private String name;
	private int imageId;

	Animal(String name, int imageId) {
		this.name = name;
		this.imageId = imageId;
	}

	public String getName() {
		return name;
	}

	public int getImageId() {
		return imageId;
	}
}

Here, we have created a modal class that accepts name and image id while creating an object of this class.

(b) Create a new xml file, named list_item.xml, for adapter of RecyclerView in res/layout folder. Then, open this file (list_item.xml) and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/bg_list_item"
    android:orientation="vertical"
    android:padding="@dimen/list_padding">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:orientation="vertical"
        android:padding="@dimen/padding_minimum">

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/margin_bottom"
            android:textSize="@dimen/text_size_default"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/image"
            android:layout_width="@dimen/img_width"
            android:layout_height="@dimen/img_height" />

    </LinearLayout>

</LinearLayout>

In each item of recyclerView, there will be one imageView and textView. So, we have designed the view accordingly.

(c) Now, create a new java file, named RecyclerViewAdapter.java, in main/java/com.tutorialwing.butterknife/recyclerview package. Then, open this new file and add below code into it.

package com.tutorialwing.butterknifetutorial.recyclerview;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.tutorialwing.butterknifetutorial.R;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

	private List<Animal> animals;
	private int rowLayout;

	RecyclerViewAdapter(List<Animal> animals, int rowLayout) {
		this.animals = animals;
		this.rowLayout = rowLayout;
	}

	@NonNull
	@Override
	public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
		return new ViewHolder(view);
	}

	@Override
	public void onBindViewHolder(ViewHolder holder, final int position) {
		holder.name.setText(animals.get(position).getName());
		holder.imageView.setImageResource(animals.get(position).getImageId());
	}

	@Override
	public int getItemCount() {
		return animals.size();
	}

	static class ViewHolder extends RecyclerView.ViewHolder {

		@BindView(R.id.name)
		TextView name;

		@BindView(R.id.image)
		ImageView imageView;

		ViewHolder(View v) {
			super(v);
			ButterKnife.bind(this, v);
		}
	}
}

Notice how we have defined and used butterknife library in adapter class to bind the view in ViewHolder class.

Now, we will create an activity and it’s xml file to use recyclerView in it. The adapter class which we just created will be used by this recyclerView.

(d) Create a new xml file, named activity_example_adapter.xml, in res/layout folder. Then, add below code into newly created xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical">

	<android.support.v7.widget.RecyclerView
		android:id="@+id/recyclerView"
		android:layout_width="match_parent"
		android:layout_height="match_parent">

	</android.support.v7.widget.RecyclerView>

</LinearLayout>

In this file, we have defined recyclerView. we will access this recyclerView in java file to perform some operations in it.

(e) Create a new java file, named ExampleAdapterActivity.java, in main/java/com.tutorialwing.butterknife/recyclerview package. Then, add below code into newly created file.

package com.tutorialwing.butterknifetutorial.recyclerview;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.tutorialwing.butterknifetutorial.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ExampleAdapterActivity extends AppCompatActivity {

	@BindView(R.id.recyclerView)
	RecyclerView recyclerView;

    private Unbinder unbinder;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_example_adapter);

		unbinder = ButterKnife.bind(this);

		//This is to show data for first time when we run the app.
		recyclerView.setLayoutManager(new GridLayoutManager(this, 2));

		List<Animal> animalList = new ArrayList<>();
		animalList.add(new Animal("Ant", R.drawable.ant));
		animalList.add(new Animal("Ape", R.drawable.ape));
		animalList.add(new Animal("Baboon", R.drawable.baboon));
		animalList.add(new Animal("Beaver", R.drawable.beaver));
		animalList.add(new Animal("Bee", R.drawable.bee));
		animalList.add(new Animal("Boar", R.drawable.boar));
		animalList.add(new Animal("Camel", R.drawable.camel));
		animalList.add(new Animal("Donkey", R.drawable.donkey));

		recyclerView.setAdapter(new RecyclerViewAdapter(animalList, R.layout.list_item));
	}

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unbinder.unbind();
    }
}

These recyclerView part described here is acting as a driver program to show how will you use butterKnife library in adapter class.



3. MainActivity to Run all Examples Described Above

Till now, we have seen how to use android butterknife library for view binding in different scenarios. But, we did not see them as demo running in the application. So, we will modify code in MainActivity.java and activity_main.xml files to show all the examples running in the example. So,

(a) Open main/res/layout/activity_main.xml file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
	android:id="@+id/rootLayout"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical"
	android:padding="@dimen/padding_default">

	<RelativeLayout
		android:layout_width="match_parent"
		android:layout_height="match_parent">

		<Button
			android:id="@+id/use_activity"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_marginTop="@dimen/padding_large"
			android:text="@string/use_in_activity"/>

		<Button
			android:id="@+id/use_fragment"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@id/use_activity"
			android:text="@string/use_in_fragment"/>

		<Button
			android:id="@+id/use_recyclerview"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@id/use_fragment"
			android:text="@string/use_in_adapter"/>

		<Button
			android:id="@+id/use_listener"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@id/use_recyclerview"
			android:text="@string/use_as_listener"/>

		<Button
			android:id="@+id/use_resource"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@id/use_listener"
			android:text="@string/use_for_resources"/>

		<Button
			android:id="@+id/use_multiple_views"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@id/use_listener"
			android:text="@string/use_for_multiple_views"/>

	</RelativeLayout>

</FrameLayout>

Here, each button represents a different example. Clicking on it will redirect you to new activity.

(b) Open main/java/com.tutorialwing.butterknife/MainActivity.java file. Then, add below code into it.

package com.tutorialwing.butterknifetutorial;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.tutorialwing.butterknifetutorial.recyclerview.ExampleAdapterActivity;

import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class MainActivity extends AppCompatActivity {

    private Unbinder unbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        unbinder = ButterKnife.bind(this);
    }

    @OnClick({R.id.use_activity, R.id.use_fragment, R.id.use_recyclerview, R.id.use_listener, R.id.use_resource, R.id.use_multiple_views})
    void onClick(View view) {
        Class<?> activityCls = null;
        switch (view.getId()) {
            case R.id.use_activity:
                activityCls = ExampleActivity.class;
                break;
            case R.id.use_recyclerview:
                activityCls = ExampleAdapterActivity.class;
                break;
            case R.id.use_listener:
                activityCls = ExampleListenerActivity.class;
                break;
            case R.id.use_resource:
                activityCls = ExampleResourceActivity.class;
                break;
            case R.id.use_multiple_views:
                activityCls = ExampleMultipleViewActivity.class;
                break;
            case R.id.use_fragment:
                getFragmentManager().beginTransaction()
                        .add(R.id.rootLayout, new ExampleFragment())
                        .addToBackStack(null)
                        .commit();
                break;
        }

        if (activityCls != null) {
            startActivity(new Intent(MainActivity.this, activityCls));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unbinder.unbind();
    }
}

Here, we have accessed all the buttons defined in xml file. Clicking on any button redirects control to new activity to show a different example of android butterknife library.

AndroidManifest.xml file

Since AndroidManifest.xml file is very important file in any android application. It’s better to see the final content in it. Our AndroidManifest.xml file would look like below.

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.butterknifetutorial"
		  xmlns:android="http://schemas.android.com/apk/res/android">

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">
		<activity android:name=".MainActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
		<activity android:name=".ExampleActivity">
		</activity>
		<activity android:name=".recyclerview.ExampleAdapterActivity">
		</activity>
		<activity android:name=".ExampleListenerActivity">
		</activity>
		<activity android:name=".ExampleResourceActivity">
		</activity>
		<activity android:name=".ExampleMultipleViewActivity">
		</activity>
	</application>

</manifest>

Now, run the application. You will get the output as shown above.

4. Different Annotations Available in ButterKnife Library

Different annotations available in android butterKnife library are –

Name Description Example
@BindView This is used to bind a view with given id. For example, @BindView(R.id.button) to bind view with id button. Example
@BindViews This is used to bind multiple views with given ids. For Example, @BindViews(R.id.button1, R.id.button2) to bind views with id button1 and button2. Example
@BindString This is used to bind string resource with given id. For example, @BindString(R.string.message) to bind string with name message Example
@BindDimen This is used to bind dimension resource with given name. For Example, @BindDimen(R.dimen.width) to get a dimension with name width. Example
@BindColor This is used to bind color resource with given name. For example, @BindColor(R.color.green) to bind a color with name green. Example
@OnClick This is used to set click listener on view with given id. For Example, @OnClick(R.id.button1) to set click listener on view with id button1. Example

This completes our tutorial on android Butterknife library for view binding with example. You can also visit official site of this library to learn more.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners