ButterKnife: The Right Way [Part 2]

Previously in part one, we talked about different annotations available in ButterKnife. Please read part one to know the reason behind this article. We previously talked about Resource Binding and View Binding and left with @BindViews in which we can bind multiple views in a List or Array. There are three convenience methods for working with view list or array.

  1. apply(List, Action) – Applies an action to each view.
  2. apply(List, Setter, Object) – Applies a setter value to each view.
  3. apply(List, Property, Object) – Applies a property value to each view.

Let’s look at ’em one by one.
I’ll bind some country names inside CheckBox[].

@BindViews({R.id.cbAmerica, R.id.cbBritain, R.id.cbChina, R.id.cbIndia})
CheckBox[] countries;


Now suppose we want to check all of the views then we have to iterate through all views and check each one by one which is a lot of repeated work. Luckily, Butter Knife fulfils this requirement out-of-the-box. Let’s see how we can do this with the help of Action.

First, we’ll create an Action and with the help of Butterknife.apply() method we’ll call created Action.

final Action<CheckBox> CHECK_ALL = new Action<>() {
 public void apply(@NonNull CheckBox checkBox, int index) {

and whenever we want to apply this action all we have to do is passCHECK_ALL action to apply and it will handle all the dirty work for us.

void selectAll() {
 ButterKnife.apply(countries, CHECK_ALL);


If there is a Select All button there will always be a Clear All button so what if we need to implement its functionality? Are we gonna create another Action for it? that would be one way to do it. A Setter would be more suitable here. A Setter behaves just like an Action but actually allows passing values. Instead of having two Action, we could make use of a Setter. Creating a Setter is same as creating an Action.

final Setter<CheckBox, Boolean> CHECKED = new Setter<> () {
 public void set(@NonNull CheckBox view, Boolean value, int index) {
  checkBox.setChecked(value != null ? value : false);

and to set the property just call

void selectAll() {
 ButterKnife.apply(countries, CHECKED, true); // false in case of uncheck

The above code is self-explanatory all we need to do is pass the condition that setter will get in its set(view, boolean, int) implementation and will use this to switch to check and uncheck our checkboxes.


Butter Knife also allows you to apply Property values when available. The View class has the following properties defined:


Applying a Property is same as applying Action or Setter.

void fade() {
 ButterKnife.apply(translucentViews, View.ALPHA, 0.5 f);

That’s all for now! We’ll continue to explore other libraries in our future posts. If you liked this series on ButterKnife please SHARE, It keeps me going.

Leave a Reply

Your email address will not be published. Required fields are marked *