How to use Butter Knife Actions in your Android App

If you’re an Android developer you’ve probably heard of Butter Knife.

Butter Knife makes binding your views in code really easy — no more pesky findViewById calls!

It also has bunch more bindings for methods like OnClickListener and OnTouchListener etc.

But there is a little-known feature you may not have heard of:

Butter Knife Actions

Butter Knife Actions work in conjunction with binding multiple views into a list of views:

@BindViews({ R.id.product_name, R.id.product_description, R.id.product_price })

List<TextView> productViews;

Using Actions, you can apply an action to all views at once. Cool right?

ButterKnife.apply(productViews, View.ALPHA, 0.0f);

Actions work on Android View Properties like:

Alpha

Translation

Scale

etc

But what if you want custom actions?

Custom Actions

Toggling view visibility is something you probably do a lot, and often on multiple views at once.

While Actions don’t support this out of the box, we can write a custom action to make this super easy.

We have 2 options here: a custom action, or a custom setter.

An action will simply perform an action on a view. For example set the visibility to GONE, or set text to null.

//custom action

public static final ButterKnife.Action<View> GONE = new ButterKnife.Action<View>() {



@Override

public void apply(View view, int index) {

view.setVisibility(View.GONE);

}

}; //usage

ButterKnife.apply(productViews, GONE);

A setter is more flexible, and supports parameters.

Setting a views visibility is better suited to a setter — we can create one setter rather than 3 separate actions:

//custom setter

public static final ButterKnife.Setter<View, Integer> VISIBILITY = new ButterKnife.Setter<View, Integer>() {

@Override

public void set(@NonNull View view, Integer value, int index) {

view.setVisibility(value);

}

}; //usage:

//with a setter we can pass an extra visibility parameter

ButterKnife.apply(productViews, VISIBILITY, View.VISIBLE);

What are you waiting for?

Instead of doing this:

productName.setVisibility(View.GONE);

productPrice.setVisibility(View.GONE);

productDescription.setVisibility(View.GONE);

Do this:

ButterKnife.apply(productViews, VISIBILITY, View.GONE);

Your code will love you for it ❤️