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 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:
But what if you want 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 actionpublic static final ButterKnife.Action<View> GONE = new ButterKnife.Action<View>() {
@Override
public void apply(View view, int index) {
view.setVisibility(View._GONE_);
}
};
//usageButterKnife.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 setterpublic static final ButterKnife.Setter<View, Integer> VISIBILITY = new ButterKnife.Setter<View, Integer>() {@Overridepublic void set(@NonNull View view, Integer value, int index) {view.setVisibility(value);}};
//usage://with a setter we can pass an extra visibility parameterButterKnife.apply(productViews, VISIBILITY, View.VISIBLE);
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 ❤️
If you liked this article make sure to give it a few 👏’s, and follow me on twitter.