List Formatter in Android

Android internationalization/ localisation

When you are addressing a larger audience of distinct linguistic, and cultural behaviours it is essential that your application content evolve according to the preferences that the user locale demands. especially dealing with strings or human-readable text that is displayed in the user interface, the aspect of translating and formatting it to adapt the usage corresponding to the user default locale turns out to be vital as it ensures a smooth user experience.

Need for list formatter

While generating a message from an arbitrarily sized list of terms/strings/units we might have to reformat them as conjunctions or disjunctions. The choice and positioning of separators and connectors ( conjunction/ disjunction ) can differ depending on the locale

for example, consider a list of string

val language = ["Kotlin", "Java", "XML"]

where you want to generate a message by the conjunction of all items in language list, like “Kotlin, Java, and XML used in Android development ”

Looks pretty straightforward to join string using a separator (, ) and connect the penultimate one with a connector but actual structure and usage varies according to locale (refer table below)

ListFormatter Class

ListFormatter is an immutable java class written inside the package android.icu.text used to format lists of items with a separator and connectors appropriate for a given locale

create an instance of list formatter using getInstance() method either by passing the required locale along with width and type for formatting. By default it uses default locale along with conjunction as type and wide as width

getInstance(Localelocale,ListFormatter.Typetype,ListFormatter.Widthwidth)
val formatter = ListFormatter.getInstance(Locale.getDefault())

Overview about parameters

Locale

use Locale.getDefault() to get the default locale based on user device or custom locale depends upon your use case

Type

specified according to the type of meaning expressed by the list, Type Enum inside ListFormatter class ( ListFormatter.Type )

Width

controls the verbosity level of connectors, determines the size (width) of the string returned

To sum up

Inline function for list formatting

Got any questions? Leave a comment below or connect me through Twitter.. :)