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.
apply(List, Action
– Applies an action to each view.apply(List, Setter, Object
– Applies a setter value to each view.apply(List, Property, Object
– Applies a property value to each view.
Let’s cut the Rope… (oops Crap) and start coding
I’ll bind some country names inside CheckBox[].
Action
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 fulfills 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
.
All we have to do is call CHECK_ALL
action and it will handle all the dirty work for us.
Setter
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
.
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.
Proparties
Butter Knife also allows you to apply Property
values when available. The View
class has the following properties defined:
ALPHA
, TRANSLATION_X
, TRANSLATION_Y
, TRANSLATION_Z
, X
, Y
, Z
, ROTATION
, ROTATION_X
, ROTATION_Y
, SCALE_X
, SCALE_Y
Applying a Property
is same as applying Action
or Setter
.
That's all for now! We’ll continue exploring ButterKnife in our future posts. If you liked this series on ButterKnife please 👏, It keeps me going.