Text converters in data binding

Android applications often need to display different attributes in TextViews. Part of those attributes are not simple Strings, which might cause some problems. Let’s assume we have an object User with a birth date field.

Now, if user’s birth date needs to be displayed, there are several approaches.

Standard approach

In the standard approach, DateTime is converted into String by using DateTimeFormatter with a predefined pattern. Later, output printed by formatter is set to the desired TextView. This implementation works fine, but there are some obvious cons. Whenever another class requires TextView with a date in exactly the same format the code needs to be duplicated. Boilerplate code is used for setting simple text in TextView, which makes the whole class less readable. Just a few minor adjustments will make the standard approach more flexible and elegant.

Approach with binding

By implementing databinding, finding TextView and setting text manually is not needed. Formatted text set to mBirthDate field is automatically assigned to TextView in a layout. However, it is still necessary to create DateTimeFormatter inside ViewModel.

Approach with binding and text converter

After creating a simple Converter interface, BirthDateConverter is implemented. It simply implements Converter interface, which converts a given type into a desired type, in this example, it converts DateTime into formatted String.

ViewModel injects BirthDateConverter and uses it to assign value to mBirthDate field. This approach is much more flexible as it allows us to change the formatting pattern in all ViewModels that use BirthDateConverter with a simple change in BirthDateConverter.

Approach with binding, binding adapter and text converter

In this approach, BindingAdapter is created. It receives TextView, Converter and Value and simply sets the converted value on a given TextView. XML was changed to make use of the new BindingAdapter method. This way code is much cleaner and flexible. Birth date format can be changed easily by either modifying the existing BirthDateConverter or creating a new one.

Text converter examples

BirthDateToAgeConverter converts birth date DateTime into age. This way ViewModel does not need an additional field for age which needs to be calculated and stored only for display purposes.

CurrencyConverter displays money amount with currency name and the display format can be easily modified.

Conclusion

Using text converters allows us to write clean and flexible code. When converting format is changed we do not have to search through the whole project to change every instance conversion method. Instead, a simple change to Converter class is that’s needed. In combination with BindingAdapter text converters shorten code to the minimum. You can find an example of a project with all converters here: https://github.com/rstit/android-text-converters