-
Notifications
You must be signed in to change notification settings - Fork 4
Value Converters: writing a custom value converter
Value converters are methods that you can use to bind data to views, but in the format that the views natively don't understand. For example, one of the converters in the library converts a Boolean
into a View.VISIBILITY
, which then enables you to bind a Boolean
directly to the Visibility
property of a View
. It is used like this: {Visibility @= ToVisibility(ViewVisible)}
, where ToVisibility
is the converter's name and the ViewVisible
is the name of the bound data or method (with added get
prefix, so it becomes getViewVisible
).
Let's examine the anatomy of a Value Converter.
First, it needs to implement a solutions.alterego.androidbound.converters.interfaces.IValueConverter
interface, that has only two methods:
Object convert(Object value, Class<?> targetType, Object param, Locale locale);
Object convertBack(Object value, Class<?> targetType, Object param, Locale locale);
Converters that bind only in the direction of a View use the convert
method, and binding in the direction from the View to the Object/ViewModel uses convertBack
.
Parameters are always the same, and beyond the obvious ones - value
for the bound data and targetType
for the View class - there's also a param
, which is an optional parameter that can be passed to the converter. For example, ToVisibility
converter supports the invert
parameter,that inverts the boolean
value so that true
sets the view visibility to View.GONE
instead of View.VISIBLE
. There's also the locale
parameter that you can use if you need the Locale to perform your conversions.
Second, your custom converter also needs to be registered with the ViewBinder
so that it knows about it. That's easily done through registerConverter(String name, IValueConverter converter)
method, that takes a name - with which you will call the converter from XML - and your custom converter reference.