MessageFormat Class

Definition

<strong>[icu enhancement]</strong> ICU's replacement for java.text.MessageFormat.

[Android.Runtime.Register("android/icu/text/MessageFormat", ApiSince=24, DoNotGenerateAcw=true)]
public class MessageFormat : Android.Icu.Text.UFormat
[<Android.Runtime.Register("android/icu/text/MessageFormat", ApiSince=24, DoNotGenerateAcw=true)>]
type MessageFormat = class
    inherit UFormat
Inheritance
MessageFormat
Attributes

Remarks

<strong>[icu enhancement]</strong> ICU's replacement for java.text.MessageFormat.&nbsp;Methods, fields, and other functionality specific to ICU are labeled '<strong>[icu]</strong>'.

MessageFormat prepares strings for display to users, with optional arguments (variables/placeholders). The arguments can occur in any order, which is necessary for translation into languages with different grammars.

A MessageFormat is constructed from a <em>pattern</em> string with arguments in {curly braces} which will be replaced by formatted values.

MessageFormat differs from the other Format classes in that you create a MessageFormat object with one of its constructors (not with a getInstance style factory method). Factory methods aren't necessary because MessageFormat itself doesn't implement locale-specific behavior. Any locale-specific behavior is defined by the pattern that you provide and the subformats used for inserted arguments.

Arguments can be named (using identifiers) or numbered (using small ASCII-digit integers). Some of the API methods work only with argument numbers and throw an exception if the pattern has named arguments (see #usesNamedArguments()).

An argument might not specify any format type. In this case, a Number value is formatted with a default (for the locale) NumberFormat, a Date value is formatted with a default (for the locale) DateFormat, and for any other value its toString() value is used.

An argument might specify a "simple" type for which the specified Format object is created, cached and used.

An argument might have a "complex" type with nested MessageFormat sub-patterns. During formatting, one of these sub-messages is selected according to the argument value and recursively formatted.

After construction, a custom Format object can be set for a top-level argument, overriding the default formatting and parsing behavior for that argument. However, custom formatting can be achieved more simply by writing a typeless argument in the pattern string and supplying it with a preformatted string value.

When formatting, MessageFormat takes a collection of argument values and writes an output string. The argument values may be passed as an array (when the pattern contains only numbered arguments) or as a Map (which works for both named and numbered arguments).

Each argument is matched with one of the input values by array index or map key and formatted according to its pattern specification (or using a custom Format object if one was set). A numbered pattern argument is matched with a map key that contains that number as an ASCII-decimal-digit string (without leading zero).

<h3>"patterns">Patterns and Their Interpretation</h3>

MessageFormat uses patterns of the following form: <blockquote>

message = messageText (argument messageText)*
            argument = noneArg | simpleArg | complexArg
            complexArg = choiceArg | pluralArg | selectArg | selectordinalArg

            noneArg = '{' argNameOrNumber '}'
            simpleArg = '{' argNameOrNumber ',' argType [',' argStyle] '}'
            choiceArg = '{' argNameOrNumber ',' "choice" ',' choiceStyle '}'
            pluralArg = '{' argNameOrNumber ',' "plural" ',' pluralStyle '}'
            selectArg = '{' argNameOrNumber ',' "select" ',' selectStyle '}'
            selectordinalArg = '{' argNameOrNumber ',' "selectordinal" ',' pluralStyle '}'

            choiceStyle: see {@link ChoiceFormat}
            pluralStyle: see {@link PluralFormat}
            selectStyle: see {@link SelectFormat}

            argNameOrNumber = argName | argNumber
            argName = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
            argNumber = '0' | ('1'..'9' ('0'..'9')*)

            argType = "number" | "date" | "time" | "spellout" | "ordinal" | "duration"
            argStyle = "short" | "medium" | "long" | "full" | "integer" | "currency" | "percent" | argStyleText

</blockquote>

<ul> <li>messageText can contain quoted literal strings including syntax characters. A quoted literal string begins with an ASCII apostrophe and a syntax character (usually a {curly brace}) and continues until the next single apostrophe. A double ASCII apostrophe inside or outside of a quoted string represents one literal apostrophe. <li>Quotable syntax characters are the {curly braces} in all messageText parts, plus the '#' sign in a messageText immediately inside a pluralStyle, and the '|' symbol in a messageText immediately inside a choiceStyle. <li>See also MessagePattern.ApostropheMode<li>In argStyleText, every single ASCII apostrophe begins and ends quoted literal text, and unquoted {curly braces} must occur in matched pairs. </ul>

Recommendation: Use the real apostrophe (single quote) character \\u2019 for human-readable text, and use the ASCII apostrophe (\\u0027 ' ) only in program syntax, like quoting in MessageFormat. See the annotations for U+0027 Apostrophe in The Unicode Standard.

The choice argument type is deprecated. Use plural arguments for proper plural selection, and select arguments for simple selection among a fixed set of choices.

The argType and argStyle values are used to create a Format instance for the format element. The following table shows how the values map to Format instances. Combinations not shown in the table are illegal. Any argStyleText must be a valid pattern string for the Format subclass used.

<table border=1> <tr> <th>argType <th>argStyle <th>resulting Format object <tr> <td colspan=2>(none)<td>null<tr> <td rowspan=5>number<td>(none)<td>NumberFormat.getInstance(getLocale())<tr> <td>integer<td>NumberFormat.getIntegerInstance(getLocale())<tr> <td>currency<td>NumberFormat.getCurrencyInstance(getLocale())<tr> <td>percent<td>NumberFormat.getPercentInstance(getLocale())<tr> <td>argStyleText<td>new DecimalFormat(argStyleText, new DecimalFormatSymbols(getLocale()))<tr> <td rowspan=6>date<td>(none)<td>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())<tr> <td>short<td>DateFormat.getDateInstance(DateFormat.SHORT, getLocale())<tr> <td>medium<td>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())<tr> <td>long<td>DateFormat.getDateInstance(DateFormat.LONG, getLocale())<tr> <td>full<td>DateFormat.getDateInstance(DateFormat.FULL, getLocale())<tr> <td>argStyleText<td>new SimpleDateFormat(argStyleText, getLocale())<tr> <td rowspan=6>time<td>(none)<td>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())<tr> <td>short<td>DateFormat.getTimeInstance(DateFormat.SHORT, getLocale())<tr> <td>medium<td>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())<tr> <td>long<td>DateFormat.getTimeInstance(DateFormat.LONG, getLocale())<tr> <td>full<td>DateFormat.getTimeInstance(DateFormat.FULL, getLocale())<tr> <td>argStyleText<td>new SimpleDateFormat(argStyleText, getLocale())<tr> <td>spellout<td>argStyleText (optional)<td>new RuleBasedNumberFormat(getLocale(), RuleBasedNumberFormat.SPELLOUT) <br>&nbsp;&nbsp;&nbsp;&nbsp;.setDefaultRuleset(argStyleText);<tr> <td>ordinal<td>argStyleText (optional)<td>new RuleBasedNumberFormat(getLocale(), RuleBasedNumberFormat.ORDINAL) <br>&nbsp;&nbsp;&nbsp;&nbsp;.setDefaultRuleset(argStyleText);<tr> <td>duration<td>argStyleText (optional)<td>new RuleBasedNumberFormat(getLocale(), RuleBasedNumberFormat.DURATION) <br>&nbsp;&nbsp;&nbsp;&nbsp;.setDefaultRuleset(argStyleText);</table>

<h4>"diffsjdk">Differences from java.text.MessageFormat</h4>

The ICU MessageFormat supports both named and numbered arguments, while the JDK MessageFormat only supports numbered arguments. Named arguments make patterns more readable.

ICU implements a more user-friendly apostrophe quoting syntax. In message text, an apostrophe only begins quoting literal text if it immediately precedes a syntax character (mostly {curly braces}).<br> In the JDK MessageFormat, an apostrophe always begins quoting, which requires common text like "don't" and "aujourd'hui" to be written with doubled apostrophes like "don''t" and "aujourd''hui". For more details see MessagePattern.ApostropheMode.

ICU does not create a ChoiceFormat object for a choiceArg, pluralArg or selectArg but rather handles such arguments itself. The JDK MessageFormat does create and use a ChoiceFormat object (new ChoiceFormat(argStyleText)). The JDK does not support plural and select arguments at all.

<h4>Usage Information</h4>

Here are some examples of usage: <blockquote>

Object[] arguments = {
                7,
                new Date(System.currentTimeMillis()),
                "a disturbance in the Force"
            };

            String result = MessageFormat.format(
                "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
                arguments);

<em>output</em>: At 12:30 PM on Jul 3, 2053, there was a disturbance
                      in the Force on planet 7.

</blockquote> Typically, the message format will come from resources, and the arguments will be dynamically set at runtime.

Example 2: <blockquote>

Object[] testArgs = { 3, "MyDisk" };

            MessageFormat form = new MessageFormat(
                "The disk \"{1}\" contains {0} file(s).");

            System.out.println(form.format(testArgs));

            // output, with different testArgs
<em>output</em>: The disk "MyDisk" contains 0 file(s).
<em>output</em>: The disk "MyDisk" contains 1 file(s).
<em>output</em>: The disk "MyDisk" contains 1,273 file(s).

</blockquote>

For messages that include plural forms, you can use a plural argument:

MessageFormat msgFmt = new MessageFormat(
                "{num_files, plural, " +
                "=0{There are no files on disk \"{disk_name}\".}" +
                "=1{There is one file on disk \"{disk_name}\".}" +
                "other{There are # files on disk \"{disk_name}\".}}",
                ULocale.ENGLISH);
            Map args = new HashMap();
            args.put("num_files", 0);
            args.put("disk_name", "MyDisk");
            System.out.println(msgFmt.format(args));
            args.put("num_files", 3);
            System.out.println(msgFmt.format(args));

<em>output</em>:
            There are no files on disk "MyDisk".
            There are 3 files on "MyDisk".

See PluralFormat and PluralRules for details.

<h4>"synchronization">Synchronization</h4>

MessageFormats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

Java documentation for android.icu.text.MessageFormat.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

MessageFormat(IntPtr, JniHandleOwnership)
MessageFormat(String, Locale)

Constructs a MessageFormat for the specified locale and pattern.

MessageFormat(String, ULocale)

Constructs a MessageFormat for the specified locale and pattern.

MessageFormat(String)

Constructs a MessageFormat for the default FORMAT locale and the specified pattern.

Properties

ApostropheMode
ArgumentNames

<strong>[icu]</strong> Returns the top-level argument names.

Class

Returns the runtime class of this Object.

(Inherited from Object)
Handle

The handle to the underlying Android instance.

(Inherited from Object)
JniIdentityHashCode (Inherited from Object)
JniPeerMembers
Locale

Returns the locale that's used when creating or comparing subformats. -or- Sets the locale to be used for creating argument Format objects.

PeerReference (Inherited from Object)
ThresholdClass
ThresholdType
ULocale

<strong>[icu]</strong> Returns the locale that's used when creating argument Format objects.

Methods

ApplyPattern(String, MessagePattern+ApostropheMode)
ApplyPattern(String)

Sets the pattern used by this message format.

AutoQuoteApostrophe(String)

<strong>[icu]</strong> Converts an 'apostrophe-friendly' pattern into a standard pattern.

Clone()

Creates and returns a copy of this object.

(Inherited from _Format)
Dispose() (Inherited from Object)
Dispose(Boolean) (Inherited from Object)
Equals(Object)

Indicates whether some other object is "equal to" this one.

(Inherited from Object)
Format(IDictionary<String,Object>, StringBuffer, FieldPosition)

Formats a map of objects and appends the MessageFormat's pattern, with arguments replaced by the formatted objects, to the provided StringBuffer.

Format(Object, StringBuffer, FieldPosition)

Formats a map or array of objects and appends the MessageFormat's pattern, with format elements replaced by the formatted objects, to the provided StringBuffer.

Format(Object)

Formats an object to produce a string.

(Inherited from _Format)
Format(Object[], StringBuffer, FieldPosition)

Formats an array of objects and appends the MessageFormat's pattern, with arguments replaced by the formatted objects, to the provided StringBuffer.

Format(String, IDictionary<String,Object>)

Creates a MessageFormat with the given pattern and uses it to format the given arguments.

Format(String, Object[])
FormatToCharacterIterator(Object)

Formats an Object producing an AttributedCharacterIterator.

(Inherited from _Format)
GetFormatByArgumentName(String)

<strong>[icu]</strong> Returns the first top-level format associated with the given argument name.

GetFormats()

Returns the Format objects used for the format elements in the previously set pattern string.

GetFormatsByArgumentIndex()

Returns the Format objects used for the values passed into format methods or returned from parse methods.

GetHashCode()

Returns a hash code value for the object.

(Inherited from Object)
JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object)
Notify()

Wakes up a single thread that is waiting on this object's monitor.

(Inherited from Object)
NotifyAll()

Wakes up all threads that are waiting on this object's monitor.

(Inherited from Object)
Parse(String, ParsePosition)

Parses the string.

Parse(String)

Parses text from the beginning of the given string to produce an object array.

ParseObject(String, ParsePosition)

Parses text from a string to produce an object array or Map.

ParseObject(String)

Parses text from the beginning of the given string to produce an object.

(Inherited from _Format)
ParseToMap(String, ParsePosition)

<strong>[icu]</strong> Parses the string, returning the results in a Map.

ParseToMap(String)

<strong>[icu]</strong> Parses text from the beginning of the given string to produce a map from argument to values.

SetFormat(Int32, _Format)

Sets the Format object to use for the format element with the given format element index within the previously set pattern string.

SetFormatByArgumentIndex(Int32, _Format)

Sets the Format object to use for the format elements within the previously set pattern string that use the given argument index.

SetFormatByArgumentName(String, _Format)

<strong>[icu]</strong> Sets the Format object to use for the format elements within the previously set pattern string that use the given argument name.

SetFormats(_Format[])

Sets the Format objects to use for the format elements in the previously set pattern string.

SetFormatsByArgumentIndex(_Format[])

Sets the Format objects to use for the values passed into format methods or returned from parse methods.

SetFormatsByArgumentName(IDictionary<String,_Format>)

<strong>[icu]</strong> Sets the Format objects to use for the values passed into format methods or returned from parse methods.

SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object)
SetLocale(ULocale)

Sets the locale to be used for creating argument Format objects.

ToArray<T>() (Inherited from Object)
ToPattern()

Returns the applied pattern string.

ToString()

Returns a string representation of the object.

(Inherited from Object)
UnregisterFromRuntime() (Inherited from Object)
UsesNamedArguments()

<strong>[icu]</strong> Returns true if this MessageFormat uses named arguments, and false otherwise.

Wait()

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>.

(Inherited from Object)
Wait(Int64, Int32)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)
Wait(Int64)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

JavaCast<TResult>(IJavaObject)

Performs an Android runtime-checked type conversion.

JavaCast<TResult>(IJavaObject)
GetJniTypeName(IJavaPeerable)

Gets the JNI name of the type of the instance self.

JavaAs<TResult>(IJavaPeerable)

Try to coerce self to type TResult, checking that the coercion is valid on the Java side.

TryJavaCast<TResult>(IJavaPeerable, TResult)

Try to coerce self to type TResult, checking that the coercion is valid on the Java side.

Applies to