Better Android Development with Butterknife Library(No FindViewByIds)
Hello World. In this post, I will show you how to perform tasks simpler using one of the awesome open source Android libraries called Butterknife.
If you have been developed for Android before, you must have come across findviewbyid(where a view is defined in xml layout and you reference it in an activity, fragment or some other layout. This may seem trivial but when your views become too many for you to do the findviewbyids stuff, it becomes somehow a pain. Well, this might be the end of your pain setting up a Java/Android project and saving yourself the stress 😃.
Setting Up Butterknife project in Android Studio
From Android Studio, create a new project and select the type of Activity to be an Empty Activity or Basic Activity. Give your app any name you want. In your module level build.gradle file, add the following dependencies.
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
Make sure you sink the project after adding dependences.
Go to you activty_main.xml and change the root view to be a vertical Linearlayout and add two Edittext fields for with ids,userName and password and a Button with text Login and id as loginButton. The layout is shown below.
Referencing views in MainActivity.java with Butterknife
Now in MainActivity.java, we will not declare any private variables for the two input fields and button, instead we will use Java annotations with butterknife to bind the views as follows
Lastly, you have to call Butterknife.bind(this) in onCreate method. That is all.You can start using the views in your activity.
Also, the butterknife library saves you the stress of adding an onClick listener to the button. Using the normal way, our onClick will be as follows.
Now with butterknife, all you have to do is use the butterknife onClick annotation as follows.
That is all you need. You are done.
So at the end , your MainActivity.java should look like shown below;
Butterknife can also be used with Fragments as well as ViewHolders to ease your work. For more check the link https://github.com/JakeWharton/butterknife .
Appreciation
Great thanks goes to Jake Wharton for his great Android libraries, one of which is Butterknife