How to use ButterKnife In Andro > Android Apps/Applications Mobile Development
This example demonstrates how do I ButterKnife in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
Step 3 – Open build.gradle(Module App) and add the following dependency
Step 4 − Add the following code to src/MainActivity.java
Step 5 — Add the following code to androidManifest.xml
Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Обзор библиотеки ButterKnife.
В Android для работы с компонентами пользовательского интерфейса из активности или фрагментов приходится писать довольно много лишнего boilerplate-кода. Наверня-ка вам уже порядок надоело использовать все эти findById() с дальнейшим приведением типа. К счастью, небезызвестный Jake Wharton написал для решения этой проблемы библиотеку под названием ButterKnife. Для начала еще раз взглянем на привычный нам код без использования данной библиотеки:
Пусть у нас имеется одна активность с двумя полями EditText для ввода суммы и процентов от суммы, TextView для вывода результата и одну обычную кнопку — Button. Для инициализации всех компонентов и возможности работать с ними из кода без использования ButterKnife вы бы написали примерно следующий код:
Butterknife Andro > November 12, 2020 by Kapil Leave a Comment
Butterknife Android Library Tutorial Hi Developers, Today we will discuss how to use Butterknife Android Library by Jake WhartonAnnotate. You can annotate the fields with @BindView annotation and a view ID that Butter Knife will find and cast the views in the layout. We will create a simple app for this Butterknife android library tutorial with two views, one EditText and a Button. These two views will be part of the activity which we have named ButterknifeActivity.
Why use Butterknife Android Library?
Butterknife Android Library makes it really simple to annotate the views inflation as well as OnClickListeners(). It allows you to concentrte on the actual business logic. Butterknife will inject the code at the compile time similar to android annotations. However it is not a dependency injection library.
Thus instead of doing
you have to simply use this
for setting the OnClickListener() you do this
you can simply say
You can also bind Strings, Image and Color resources.
So let’s start creating the example app for Butterknife Android Library
Creating a Butterknife android Project
- Go to File → New → New Project and enter your Application Name.
- Enter company domain, this is used to uniquely identify your App’s package worldwide.
- Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code ourselves. Then Click on Next.
- Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have used the Activity Name as ButerknifeActivity for obvious reasons.
Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.
- Now open your project’s build.gradle from the project’s home directory and add the following dependency.
Add Layout and Functionality
We are binding the name editText using the @BindView annotation. In the onCreate() method we initailize and bind the views to the activity using the Butterknife bind method.
Next we add the OnClickListener() by using the @OnClick annotation and the method that will be executed on the click of the button. Isn’t this really simple ?
The Butterknife android example app is now complete, we will test the app by adding a name in the EditText and click on the submit button.
What’s Next ??
After integrating the Butterknife Android Library you can experiment with other useful android libraries like Dagger – a fast dependency injection library and Glide.
Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.
To download the full code for theButterknife Android Library Tutorial app, Click on the Download Now link below.
Вопрос по butterknife, andro >
Мне нужно установить плагин Butter Knife. Где я могу скачать его? Я скачал плагин .jar (но не в том случае, если файл является тем, который мне нужен), я установил, но когда я нажимаю на опцию «создать», не появляется опция использовать Butterknife. после видео-урока я изменил файлы сборки Gradle: теперь они у меня следующие:
Gradle для синхронизации я получаю эту ошибку:
Ошибка «Android android-библиотека или плагин должна быть применена к проекту» (1.0)
Что я делаю неправильно?
В Android Studio вы можете сделать это:
- Щелкните правой кнопкой мыши свой модуль
- Нажмите «Открыть настройки модуля»
- Нажмите вкладку Зависимости
- Нажмите на зеленый значок плюс
- Выберите «Зависимость библиотеки» из выпадающего списка
- Введите «Butterknife» в поле поиска и нажмите кнопку поиска
После выбора библиотеки Android Studio добавляет зависимость к вашему модулю.
Поскольку Butterknife выполняет обработку аннотаций, вы должны добавить это в build.gradle вашего модуля сразу после оператора compile для butterknife:
где номер версии в конце должен соответствовать вашей версии ножа.
Самый простой способ использовать библиотеку ButterKnife — добавить эту единственную строку на уровень вашего модуля. build.gradle список зависимостей:
Затем вы можете синхронизировать свой проект!
Я только что заметил, что Джейк Уортон обновил библиотеку с тех пор, как в последний раз использовал ее! Теперь, кажется, вам нужно добавить в два отдельных места:
В вашемПроект уровня build.gradle файл:
И, наконец, в вашеммодуль уровня build.gradle файл:
Важно, чтобы вы добавили apply plugin: ‘android-apt’ к вершине module-level build.gradle файл; Скорее всего, ниже первой строки, как это:
Я только что проверил это и работает для меня. Удачи!
Джейк Уортон только что выпустил обновление для библиотеки, и вот что вам нужно сделать, чтобы использовать его:
Итак, внутри вашего build.gradle (app-level) Добавьте следующее в ваши зависимости!
Я надеюсь, это поможет вам!
Если попытаться, если вы хотите установить минимальный уровень SDK 15 до настоящего времени, вам нужно будет поиграть с версиями, чтобы заставить его работать, в моем случае эти наборы совместимы до сих пор с SDK 15 как минимум.
Java — android butterknife
You might be getting tired of declaring variables for all of your View s at the top of your activity >id ‘s to set variables. Thankfully, there’s a tool that can assist us with this! ButterKnife, after a little setup, will cut down on redundant code. ButterKnife is an injection library that allows for field and method binding for Android views.
Currently, whenever our back-end (or «business logic»; remember that term from Intro?) needs to interact with a portion of our user interface, we need to declare indiv >onCreate() method, like this:
Using ButterKnife, we could instead simply include the >View at the top of the file, where we previously declared member variables, and rely on ButterKnife to locate the views instead of manually finding them in `onCreate():
With only three View s in our MainActivity, this may not look like a large reduction in code, but in the onCreate() method of the ButterKnife version, we only need to call the single line ButterKnife.bind(this); instead of calling findViewById() on every single element manually. As our application continues to grow in size and complexity, this will save us a lot of code.
To use ButterKnife, we’ll add special annotations specific to the ButterKnife library to our code. Java annotations are simply metadata that can be added to Java code to include additional information about a program. They’re preceded by @ . This symbol informs the compiler that what immediately follows it is an annotation. (The @Override s we see in our existing code are annotations, too!)
When our project compiles, ButterKnife looks for the @Bind annotation seen above. When it finds one, it uses the additional information prov >R.id.findRestaurantsButton ) to find the corresponding view for us, so we don’t have to explicitly do so in onCreate() .
To integrate ButterKnife into our project, we’ll first need to add the library to our app’s dependencies. We’ll place the following line into our build.gradle(Module: app) file:
Before we begin, visit ButterKnife’s documentation to read more about how it works.
Now, let’s use this powerful tool to refactor our MainActivity. We should be able to take our code from this:
We’ll implement ButterKnife into our RestaurantsActivity, too! We should be able to take our code from this:
From this point forward, we will use ButterKnife to easily bind our views, and keep our code brief and well-refactored.
For more information on Java annotations in general, check out the Annotations Basics Tutorial from Oracle.
Luis G. Valle’s blog post How ButterKnife actually works? offers an optional deeper dive on the code behind ButterKnife, for those that are curious.
Annotations: A form of metadata that can be added to Java code to include information about a program that’s not part of the program itself. For ButterKnife specifically, we’ll use the @Bind annotation.
ButterKnife: An injection library that allows for field and method binding for Android views. View documentation here.
Luis G. Valle’s blog post How ButterKnife actually works? offers an optional deeper dive on the code behind ButterKnife, for those that are curious.
For more information on Java annotations in general, check out the Annotations Basics Tutorial from Oracle.
Andro > By Ravi Tamada October 6, 2020 0 Comments
Android ButterKnife library is a view injection library that injects views into android activity / fragments using annotations. For example, @BindView annotation avoids using findViewById() method by automatically type casting the view element.
Not just view binding, butterknife provides lot of other useful options like binding strings, dimens, drawables, click events and lot more. We’ll see brief about every component offered in this article.
1. Adding ButterKnife Dependency
First thing you have to do is, add ButterKnife in your project by adding the below dependencies in your project’s app/build.gradle file. Once added, sync your project, you are good to go.
2. Basic Usage
Once the dependency is added, all the butterknife annotations will be available to import. To begin with, we’ll see how to use @BindView and @OnClick annotations.
Let’s say you have the below layout for your activity that has a TextView and a Button.
To make the views available in the activity, we need to follow the below steps.
1. Use @BindView along with the id (R.id.lbl_title) of the view while declaring the view variable.
2. Call ButterKnife.bind(this) in onCreate() method after setContentView() is called.
That’s all, the view injection happens and no need to typecast the view variable using findViewById() method anymore. Also you can see, the click event is attached just by adding @OnClick annotation before the method.
3. Using in Fragments
Using view injection in Fragment is same as Activity except the ButterKnife.bind() method changes. In addition to target parameter, we need to pass inflated view as param.
You will also have to use Unbinder to unbind the view in onDestroyView() because of the Life cycle methods of Fragment.
Below is the example usage of ButterKnife in Fragment.
4. Using in List Adapter
ButterKnife also can be used in list adapters too. Below is the example of @BindView in recyclerview’s adapter class.
5. Using with Resources – Strings, Colors, Dimens, Drawables etc.,
In addition to binding view elements, you can also bind other resources like strings (@BindString), colors (@BindColor), dimensions (@BindDimen) and drawables (@BindDrawable).
Below example demonstrates multiple annotations and their usage.
6. Adding Click Listener (Listener Binding)
We have already seen the example of @OnClick annotation, but below are variants of function params.
7. Grouping Multiple Views into List & applying action
There might be scenarios where in you want to apply some action on to group of views, like applying color, setting text or selecting all CheckBoxes at once. This can be done very easily using ButterKnife.
All you have to do is, use @BindViews annotation to store all the views into a List and using ButterKnife.Action() method to apply some operations on to all views.
In the below example, two actions are applied to group of TextViews. First, the text is set from an array of strings. Second, a color is applied to all the TextViews in the list.
Below are the list of annotations provided by ButterKnife and their usage.
|@BindView||Binds view object. TextView, Button, Spinner or any view object|
I hope we have covered most of the ButterKnife features. If you think anything more needs to be added, let’s discuss in the comments section below.
Let’s compare Butterknife and Data Binding libraries, which one is more advanced in 2020? If you’re not familiar with those two, in few words: they make your layout building experience better. And when comparing them I’ll go right from setting up and cover every basic aspect so you’ll learn how to use both of them!
For Butterknife you need to add those dependencies to build.gradle
Here you’ll just add those inside android scope in build.gradle
And then wrap all your layouts with layout tag so it’s the root tag everywhere
What you would do in plain Android framework to find views in layout is use this method
Then you cast it to the right type, keep it as local variable or save to field, this is really lots of work for big layouts
With Butterknife you can just declare fields with this annotation
And declare each view as field this way, no need for findViewById method. Now if you compare this to old school method — you saved yourself 50% of lines if you save views as fields. Twice less lines.
But still, if you have 20 views — you’ll have those 20 ugly fields on top of the class, that’s just views, how about variables etc?
Now that’s the next level, here you need to do some changes though. Replace default setContentView with this
protected void onCreate(Bundle savedInstanceState) <
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
As you see there’s some ActivityMainBinding class — this class is generated for your layouts, it’s based on layout name converted to camel case adding Binding at the end. It happens when you wrap your layout with layout tag. If you have layout called layout.xml — you’d have LayoutBinding class generated
Now to access any of your views you just use
If you realized the advantage of Data Binding already — it’s you have 2 lines of code max.You just save that binding variable as field if you need and can assess any of you fields anywhere within this class
Let’s say we have 20 views in our layout and we want them to be accessible in any method within a class, so we need to have them as fields.
With findViewById you’d have 40 lines of code, with Butterknife — 20, with DataBinding — 2. Two lines! Data Binding is obvious winner here
What Else Can Butterknife Do
If you look into Butterknife doc — basically there isn’t much more. OnClick annotation which doesn’t even need any library because you can use android:onClick attribute for your views right in XML
Resource binding, which some people use, there isn’t such in Data Binding. And basically that’s it
Where with Data Binding it’s just a beginning. You can move your logic into XML files which is more natural approach when building layouts
Let’s say you have a Movie model with 20 fields and you want to display all of them in layout. Normally you’d call setText and any other methods in Java for each movie field. With Data Binding you can do this
You add variable at the top of layout and then can set views right there. Name is a variable name in Movie class.
And to pass an object to your layout you call this method in Java, it’s generated for each of your variables
It’s not that this approach saves some lines of code, it’s that it’s more natural and you won’t need to go back and forth from Java to XML again and again when building layouts, writing Java. You just write layout, done with it, go to Java. Simple.
There’s way more Data Binding can offer, just one last thing I wanted to mention — custom attributes. You can create custom attributes for any view without actually extending those views by using Binding Adapters
One of my most favorites — imageUrl. How many times you would want for Android framework to have this attribute where you just pass image url to ImageView and it just loads it? Well, when you’re just getting started you probably do.
Look at what we can do
public static void imageUrl(ImageView v, String url)<
imageUrl is a String field variable of Movie model. We’ve just declared a custom attribute for ImageView. Once you pass movie object to your layout with binding.setMovie(movie) — your ImageView will load image url from movie object with Glide
And as for that static method — you can put it anywhere in your project you want. Literally anywhere, it will work
Data Binding came out soon after I started learning Android in 2015 so I used Butterknife for few times and when I saw Data Binding I realized — that’s the next level. Just look at simple accessing views.
Btw, if you use Kotlin — there’s Android Extensions for accessing views which works just like Data Binding, but with less overhead
Tidy and Optimize Your Java Code with Android Butter Knife
This article was updated in July 2020 to reflect updates to Android Butter Knife.
Creating code can sometimes be frustrating. Developers have to deal with redundant coding that is visually unattractive. In this article, I will introduce an injection library for Android development that can help create more beautiful code and recent updates introduced with version 8. Android Butter Knife is an open source view “injection” library for Android created by Jake Wharton.
Butter Knife is small, simple and lightweight, and it makes life as a developer easier. It allows developers to perform injection on arbitrary objects , views and OnClickListeners so they can focus on writing useful code. Consider Android Butter Knife a reduction library. It replaces findViewById with @Bind() and set^^^^Listener calls with @onClick() making code cleaner and more understandable. Butter Knife enables focus on logic instead of glue code and reduces development time by reducing redundant coding.
Configure Your Project for Android Butter Knife
Before getting started with Butter Knife, you need to configure your Android project.
Open build.gradle at project level and add the following dependency
Open build.gradle(Module:app) (module level) and add the following dependencies.
And apply the plugin:
Finally sync Gradle.
Butter Knife in action
Now that you have configured Butter Knife its time to move on to the main features this injection library can provide:
- Binding views and resources
- Event Listeners
- List adapters, RecyclerView implementation
Why use Butter Knife
The goal of this library is to help developers write better code, and it does so by trying to reduce the code used in the onCreate method on an Activity class and in onCreateView on Fragment s. All you need to write in these methods is the following:
In both the cases Butter Knife binds to the specified Android Activity or View targets to correctly act on the injections specified in these classes. All the view finding lines of code and the action listeners are implemented elsewhere, leaving these methods as clean as possible.
Binding views and resources
Butter Knife replaces the standard findViewById call with @BindView , followed by a view ID and it automatically casts the corresponding view in the corresponding layout. This representation of the code makes it more compact and readable.
Here’s an example of this “injection”:
You can do the same with app resources like String , Drawable and dimensions ( dimen , value , etc). Here are all the possible bindings with Butter Knife.
Butter Knife also makes setting event listeners of Android layout Views easy and removes the listeners implementation from the key onCreate and onCreateView methods.
Here’s an example:
This isn’t restricted to click events, here are all the other events you can set.
For the rest of this tutorial, I will focus on injecting Butter Knife features in Material Design views and components.
Open Android Studio and create an application with a Basic Activity.
What better component to test with than the FloatingActionButton .
And as you can see in the image below it works as you would expect.
Butter Knife works well with list adapters, but can it also work with other Material Design similar components such as the RecyclerView adapter?
The process of building a RecyclerView is long and complex, so I recommend you first read my article explaining how.
I will focus on the parts of the RecyclerView related to Butter Knife, the ViewHolder and view binding. The full code of this example is available on GitHub.
The ViewHolder example of a RecyclerView looks like this (In Recycler_View_Adapter.java).
This ViewHolder class represents one row of the RecyclerView with the following layout (row_layout.xml).
In an Activity class bind the RecyclerView and provide data to its Adapter (In MainActivity.java).
Android Butter Knife helps you create cleaner and tidier code, handling a lot of the ugly boilerplate code that Android has become infamous for. Have you tried in your projects? I’d love to know if you found it useful or not.
Android Butter Knife Example
In this android tutorial, we are going to learn how to use Android ButterKnife View Binding in android application development.
If you have been developing android application, you will realized that there are lots of boilerplate codes in your application that can get to the way of your main business logic. A good example is when you have like 20 View widgets in your layout file and to get the instances of these widgets in your Activity of Fragment class, you will call the findViewById() method 20 times.
In some cases, it will be too much that the onCreate() method will be bloated by boilerplate codes.
This is where Android Butterknife comes to your help. Before you start using it, the points below is how it can help improve your code.
- Eliminate findViewById calls by using @BindView on fields.
- Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties.
- Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others.
- Eliminate resource lookups by using resource annotations on fields.
A typical example of instantiating a view widget using Butterknife is as shown below.
Another important use case of Butterknife is that it is not only made for View binding. Butterknife can as well be used to bind predefine resource in your android project. Example below shows you how it can be achieved.
In addition to what we can covered, another important usage is for binding listeners. A simple example of how to bind to a Listener is shown below.
Butterknife works in a simply by using annotation to generate code that application will reference to when bind is called.
There are many other ways that you can use Butter knife. If you want to read more I will suggest you visit the official website here.
Using Butter Knife with Android RecyclerView
Now that we have a general idea of how to use Butter Knife and what it does. We will go ahead and see how we can use Butter Knife view bind in android recyclerview.
We will create a MainActivity class with it corresponding layout. Add a RecyclerView widget in the layout file. Create a new layout file that will represent the UI of each item in the recyclerview.
Furthermore, create a Recyclerview adapter class and a ViewHolder class which the recyclerview will use as its own adapter.
In other to get a visual understanding of what we are going to create in this android tutorial, I have add below some screen shots from the application.
SOME SCREENSHOT FROM THE APPLICATION
CREATE NEW ANDROID PROJECT
Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.
To create a new android application project, follow the steps as stipulated below.
Go to File menu
Click on New menu
Click on Android Application
Enter Project name: AndroidButterknifeExample
Select Empty Activity
Name your activity: MainActivity
Keep other default selections
Continue to click on next button until Finish button is active, then click on Finish Button.
Build.gradle for Dependencies and Android-apt plugin
We will move over to the build.gradle file. One thing we need to do is to add android-apt in the project level dependencies and in the Module level build.gradle, we will add the android-apt plugin below the android plugin.
Butter Knife uses the android-apt plugin because of the following reasons
1. Allow to configure a compile time only annotation processor as a dependency, not including the artifact in the final APK or library
2. Set up the source paths so that code that is generated from the annotation processor is correctly picked up by Android Studio.
Now, open your project level build.gradle and add the code below.
Also, open the module level build.gradle and add the code below.
We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.
Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.
Lets create layout file for our app UI
Open the activity_main.xml file that was created by us. If you do not select default activity creation, you can create a new activity class and name it MainActivity.java.
In the main layout file, we are going to add a RecyclerView widget. This layout is simple and easy to understands.
Open the activity_main.xml and add the code below.
Create a new layout file in the layout folder inside the res folder. Name this layout file car_layout.xml or anything you wish. This will represent the UI of each list item of the recyclerview widget we create above.
Open this layout file and add the code below
Create a new java class file in your project package folder and name it CarAdapter. The adapter will bind our data source to each item list in the recyclerview instance.
This class will inflate a layout file that we have created above which represents an item view of the recyclerview.
The inflated layout view reference will be passed as a parameter to the instance of the CarViewHolder which is created below.
Open the CarAdapter class and add the code below to it.
Create another new Java class file and name it CarViewHolder. Since this class has a reference to the car_layout.xml file we create above, we will use the Butter knife view binding to bind the View widgets in the layout file.
Open the file and add the following code to it.
Right now you can see the magic and how concise the code is.
Open the MainActivity class, we will also bind the recyclerview widget that was add to the activity_main.xml to this class as shown below
In the onCreate(Bundle savedInstanceState method of the Activity class, call bind method and pass the activity reference to it.
The remaining code is to instantiate the adapter and pass it to the recyclerview. Add the code below to the file.
The last thing to do is to create an entity class. Create a new Java class file and name it CarObject.java. Open the file and add the code below to it.
If you have any question or suggestion about Butter Knife kindly leave a message in the comment section below.
This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.
You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.
Remember to subscribe with your email address to be among the first to receive my new android blog post once it is published.
It would be helpful for you if you already know about Button, TextView, EditText and RecyclerView.
TABLE OF CONTENT
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.
You can download source code of this tutorial on android ButterKnife Library by entering the details –
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.
|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.
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.
Open res/values/dimens.xml file. Then, add below code into it.
Open res/values/colors.xml file. Then, add below code into it.
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.
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.
@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.
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.
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.
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 –
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 –
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.
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.
@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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 –
|@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.