Take Action with Butter Knife

Josh Burton
HackerNoon.com
2 min readFeb 14, 2017

--

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:

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

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.

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:

What are you waiting for?

Instead of doing this:

Do this:

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.

--

--

Josh Burton
HackerNoon.com

Freelance Android Developer. Fueled by coffee. @athornz on Twitter.