FET
FET

Reputation: 942

How to format a String Array from XML

I want to do the same thing I did here for a String resource:

write(String.format(getString(R.string.night), "Scurcola"));

but for a String Array, defined as follows:

<string-array name="goodMorning" formated="false">
    <item>Good Morning folks!</item>
    <item>Sun\'s out, guns out.</item>
    <item>Careless vampires burn, and you wake up!</item>
    <item>Can\'t find the moon. Oh it\'s probably morning then..</item>
    <item>Darkness flees from %s, wake up!</item>
    <item>Sunlight manifests, it\'s morning %s!</item>
    <item>Stars went to bed, and %s wakes up!</item>
    <item>Be beep. Be beep. %s wake up!</item>
</string-array>

How can I achieve this?

Upvotes: 1

Views: 901

Answers (2)

Phant&#244;maxx
Phant&#244;maxx

Reputation: 38098

Every array item per se is actually a string.
Therefore, each item can be individually formatted.

I.e.:

write(String.format(getResources().getStringArray(R.array.goodMorning)[0], "Scurcola"));

Upvotes: 0

FET
FET

Reputation: 942

I solved this adding this method which edits a TextView:

public void write(int id, int position, String text){
    String[] msg = getResources().getStringArray(id);
    messages.add(String.format(msg[position], text));
    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, messages);
    screen.setAdapter(adapter);
}

This way I can simply type:

write(R.array.goodMorning, randInt(0, 7), "Scurcola");

and get as output an item of the String Array, chosen randomly, thus formatted with the "Scurcola" String I passed as a parameter.

Upvotes: 1

Related Questions