Flofloaud1034
Flofloaud1034

Reputation: 388

Multiple values String format Android

I would to display text like this sample : "0/2 documents" I'm trying to do this with :

<plurals name="documents_get">
    <item quantity="one">%1d/%2d doucment</item>
    <item quantity="other">%1d/%2d documents</item>
</plurals>

resources.getQuantityString(
                    R.plurals.documents_get,
                    docCount,
                    documents.filter {

                        it.retrieved_at != null

                    }.count(),
                    docCount)

My problem is the result is : 0/ 2 documents instead "0/2 documents". Space after the '/' is the problem.

Do you know a solution for this ?

Thanks in Advance

Upvotes: 2

Views: 3806

Answers (3)

kAliert
kAliert

Reputation: 768

The problem is the format you are using (%2d). So change your plurals to this:

<plurals name="documents_get">
    <item quantity="one">%d/%d doucment</item>
    <item quantity="other">%d/%d documents</item> 
</plurals>

Example with using String.format

String s1 = String.format("%d/%d document", 0, 1); // s1: "0/1 document"
String s2 = String.format("%d/%2d document", 0, 1); // s2: "0/ 1 document"

Edit

As @Kingfisher Phuoc noted, it should be %1$d/%2$d instead of %d. The $ sign allows you to specify the index of the string (the position where the string should be printed, called "explicit argument indices" or "positional arguments". You can read more here).

For example:

String s1 = String.format("%1$d/%2$d", 1, 2); // s1: "1/2" 
String s2 = String.format("%2$d/%1$d", 1, 2); // s2: "2/1" 

Upvotes: 3

Khaled Qasem
Khaled Qasem

Reputation: 929

Remove (%2d) and replace it with (%d) or you can use string format

String resource = String.format("%d/%d document", 0, 1); // s1: "0/1 document"

Upvotes: 0

Jay Dangar
Jay Dangar

Reputation: 3479

You can define your string inside string.xml like this

<resources>
    <string name="string">0"/"2 documents</string>
</resources>

and fetch it via getResources.getString method.

Note : Special Characters are enclosed inside double quotes.

Upvotes: -2

Related Questions