Collection Custom Formatting

Intro

The collections applications allow you define your own custom fields in any collection. These fields can be Strings, numbers, dates and currency values.

Each of these fields can have their own formatting that allows you to control how the field name and value are displayed.

Note that this discussion is fairly technical, but we’ve tried to break it down using some concise examples. Don’t be afraid to experiment. If you get it badly wrong, you can always clear the format and, in error cases, it should fall back to the default format.

Defaults

By default, all the custom fields are displayed as:

‘field name’: ‘field value’

e.g.

Created date: 2017/05/01

Cost: 56.00

Custom Formats

With individual custom formats you can change this ‘name’:’value’ pairing into something else, e.g. to change the ‘cost’ example above to be:

Cost £56.00 per pack

you would write the format as:

%2$s £%1$.2f per pack

The symbols %2$s and %1$.2f are known as format specifiers. They have the following syntax:

     %[argument_index$][flags][width][.precision]conversion

Any other symbols outside of the format specifier are shown ‘as-is’ hence the ‘per pack’ becomes part of the displayed value.

The argument_indices 1 and 2 refer to the field value and field name respectively.

The conversion symbols tell the application what type of value to expect. In this case it can be one of the following:

  • s or S – The value is text. The upper case S converts the value into upper case.
  • f – The value is a decimal
  • d – The value is an integer
  • t – The value is a date

The width controls how many characters are displayed whilst the precision controls how many digits after the decimal point are shown. Note that the width includes the decimal point and the digits. If the field width is larger than the value, it will be padded with spaces. e.g.

  • £%1$.2f  is shown as £56.00
  • £%1$3.2f  is shown as £56.00
  • £%1$5.2f  is shown as £ 56.00
  • £%1$7.2f  is shown as £   56.00

Dates are very similar, but the conversion can include distinct converters for year, month and day, as well as more esoteric converters for day of year, day of week, etc. Here are some examples using the date 3rd May 2017:

  • %1$tY is shown as 2017
  • %1$tY-%1$tm is shown as 2017-05
  • %1$tY-%1$tm-%1$td is shown as 2017-05-17

There are some shortcuts for common dates, e.g.

  • %1$tF is shown as 2017-05-17 (ISO 8601)
  • %1$tD is shown as 05/17/2017 (US format)

Further Information

Custom formats are a complex subject and cannot be covered fully here. For further information, read the Android Documents for Formatter Class.