How To Perform View Binding In Android Using ButterKnife

Android
 

Introduction

 
In this article, we will learn how to perform View Binding in Android using ButterKnife which is a very useful library in Android application development. If you have been developing an Android application, you will realize that there are lots of boilerplate codes in your application. In some cases, it will be so much that the onCreate method will be bloated with boilerplate codes. This is where Android ButterKnife comes to your help.
 

ButterKnife

 
Field and method binding for Android views use annotation processing to generate boilerplate code for you. To know more, click here.
 

How it can help us to improve our code?

  1. Eliminate findViewById calls by using @BindView on fields.
  2. Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties.
  3. Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others. Eliminate resource lookups by using resource annotations on fields.
In this article, I am going to show the method for using ButterKnife with RecyclerView and Each Single Views.
 
I have divided this implementation into 4 steps, as shown in the following.
  • Step 1 - Creating a New Project with Android Studio.
  • Step 2 - Setting up the library for the project.
  • Step 3 - Implementation of ButterKnife with Single Views.
  • Step 4 - Implementation of ButterKnife with RecyclerView.
Step 1 - Creating a New Project with Android Studio
  1. Open Android Studio and select "Create a new project".
  2. Name the project as you wish and select your activity template.
     
    Android
     
  3. Click the “Finish button to create a new project in Android Studio.
Step 2 - Setting up the library for the project
  1. Open the App Level Gradle file and add the following lines to add ButterKnife Library.
    1. ...  
    2. // add the below lines in dependencies  
    3. implementation 'com.jakewharton:butterknife:8.8.1'  
    4. annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'  
    5. ...  
  1. Then, click “Sync Now” to add the library.
Step 3 - Implementation of ButterKnife with Views
 
Open your Activity and add the following line after setContentView to implement the ButterKnife.
  1. // Initialize ButterKnife   
  2. ButterKnife.bind(this);  
The Views can be initialized like below.
  1. @BindView(R.id.title)  
  2. public TextView title;  
It is replaced by the following.
  1. TextView title = findViewById(R.id.title);  
It will reduce the coding boilerplates and increases productivity.
 
Events like “ClickEvent” also be done by this library. ClickEvent can be achieved by the following lines.
  1. @OnClick(R.id.submit)  
  2. public void submit(View view) {  
  3.             // TODO submits data to server...  
  4. }  
Step 4 - Implementation of ButterKnife with RecyclerView
  1. By the same way RecyclerView, ListView also be initialized like the previous method. 
    1. @BindView(R.id.recycler)  
    2. public RecyclerView recyclerView;  
  1. To bind the data to RecyclerView, we have to create a model class and adapter with ViewHolder. The Model class and Adapter code can be find below. 
     
  2. Model Class
     
    Create a class and named as java for example, then add the following lines. 
    1. class ToDoObject {  
    2.     private String todoType;  
    3.     private String todoName;  
    4.   
    5.     ToDoObject(String todoType, String todoName) {  
    6.         this.todoType = todoType;  
    7.         this.todoName = todoName;  
    8.     }  
    9.   
    10.     String getTodoType() {  
    11.         return todoType;  
    12.     }  
    13.   
    14.     String getTodoName() {  
    15.         return todoName;  
    16.     }  
    17. }  
  1. Adapter
     
    Create an adapter for RecyclerView and named as Java, then add the following lines. 
    1. class ToDoAdapter extends RecyclerView.Adapter {  
    2.     private Context context;  
    3.     private List toDoObjectList;  
    4.   
    5.     ToDoAdapter(Context context, List toDoObjectList) {  
    6.         this.context = context;  
    7.         this.toDoObjectList = toDoObjectList;  
    8.     }  
    9.   
    10.     @Override  
    11.     public ToDoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
    12.         View view = LayoutInflater.from(context).inflate(R.layout.list_row, parent, false);  
    13.         return new ToDoViewHolder(view);  
    14.     }  
    15.   
    16.     @Override  
    17.     public void onBindViewHolder(ToDoViewHolder holder, final int position) {  
    18.         ToDoObject toDoObject = toDoObjectList.get(position);  
    19.         holder.todoType.setText(toDoObject.getTodoType());  
    20.         holder.todo.setText(toDoObject.getTodoName());  
    21.   
    22.         holder.itemView.setOnClickListener(new View.OnClickListener() {  
    23.             @Override  
    24.             public void onClick(View view) {  
    25.                 Toast.makeText(context, "Selected index " + position, Toast.LENGTH_LONG).show();  
    26.             }  
    27.         });  
    28.     }  
    29.   
    30.     @Override  
    31.     public int getItemCount() {  
    32.         return toDoObjectList.size();  
    33.     }  
    34. }  
  1. Create a ViewHolder named Java and add the following lines. 
    1. class ToDoViewHolder extends RecyclerView.ViewHolder{  
    2.   
    3.     @BindView(R.id.todo_type)  
    4.     TextView todoType;  
    5.     @BindView(R.id.todo)  
    6.     TextView todo;  
    7.   
    8.     ToDoViewHolder(View itemView) {  
    9.         super(itemView);  
    10.         ButterKnife.bind(this, itemView);  
    11.     }  
    12. }  
  1. Here, ButterKnife is initialized by the following with each Item Views. 
    1. ButterKnife.bind(this, itemView);  
  1. Views are initialized as normal view initialization methods.
  2. OnItemClick can be applied to ListView with ButterKnife and doesn’t applicable to RecyclerViews.
Full Code
 
You can find the full code implementation of the API.
  1. public class ToDoActivity extends AppCompatActivity {  
  2.   
  3.     @BindView(R.id.toolbar)  
  4.     public Toolbar toolbar;  
  5.   
  6.     @BindView(R.id.fab)  
  7.     public FloatingActionButton fab;  
  8.   
  9.     @BindView(R.id.recycler)  
  10.     public RecyclerView recyclerView;  
  11.   
  12.     @BindView(R.id.title)  
  13.     public TextView title;  
  14.   
  15.     @Override  
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.activity_main);  
  19.         ButterKnife.bind(this);  
  20.         setSupportActionBar(toolbar);  
  21.   
  22.         title.setText("ToDo List");  
  23.         title.setTextSize(20);  
  24.   
  25.         LinearLayoutManager layoutManager = new LinearLayoutManager(ToDoActivity.this);  
  26.         recyclerView.setLayoutManager(layoutManager);  
  27.         recyclerView.setHasFixedSize(true);  
  28.         ToDoAdapter mAdapter = new ToDoAdapter(ToDoActivity.this, getTestData());  
  29.         recyclerView.setAdapter(mAdapter);  
  30.   
  31.     }  
  32.   
  33.    @onClick(R.id.fab)  
  34.    public void onClick(View view) {  
  35.     Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)  
  36.             .setAction("Action"null).show();  
  37.    }  
  38.   
  39.     public List getTestData() {  
  40.         List cars = new ArrayList<>();  
  41.         cars.add(new ToDoObject("Shopping""Cake"));  
  42.         cars.add(new ToDoObject("Shopping""Cloth"));  
  43.         cars.add(new ToDoObject("Shopping""Color Paper"));  
  44.         cars.add(new ToDoObject("HomeWork""Science"));  
  45.         cars.add(new ToDoObject("HomeWork""Maths"));  
  46.         cars.add(new ToDoObject("HomeWork""Chemistry"));  
  47.         return cars;  
  48.     }  
  49.   
  50. }  
Download Code
 
You can download the full source code of the article on GitHub. If you like this article, do star the repo in GitHub. 


Similar Articles