paint-brush
Take Action with Butter Knifeby@AthorNZ
2,430 reads
2,430 reads

Take Action with Butter Knife

by Josh BurtonFebruary 14th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How to use Butter Knife Actions in your Android App

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Take Action with Butter Knife
Josh Burton HackerNoon profile picture

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 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);

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 ❤️

If you liked this article make sure to give it a few 👏’s, and follow me on twitter.