Lalit
Lalit

Reputation: 1703

How to get string in specific format in android

Suppose I want to print "Item" and its "price" in some specific format like

abc           2
asdf          4
qwer xyz      5

AND 2, 4, 5 must be like in one column.

For that i tried-

StringBuilder sb = new StringBuilder();

sb.append(String.format("%s%25s", "abc","2"));
sb.append(String.format("%s%25s", "asdf","4"));
sb.append(String.format("%s%25s", "qwer xyz","5"));

tv.setText(sb.toString());   //tv is a text view

but the output is -

abc             2
asdf             4
qwer xyz             5

I want "abc" and after 25 spaces i want "5" but it counts 25 spaces from abc not from the start

Upvotes: 4

Views: 298

Answers (2)

rekire
rekire

Reputation: 47965

You mixed up the order try this:

StringBuilder sb = new StringBuilder();

sb.append(String.format("%-25s%s", "abc","2"));
sb.append(String.format("%-25s%s", "asdf","4"));
sb.append(String.format("%-25s%s", "qwer xyz","5"));

tv.setText(sb.toString());   //tv is a text view

That minus sign before the 25 means to invert the alignment of your text. The last step is to use a monospace font. You can achieve that with this line:

tv.setTypeface(Typeface.MONOSPACE);

Upvotes: 5

Deependra Singh
Deependra Singh

Reputation: 53

You can use tab in every line. I hope it will work.

StringBuilder sb = new StringBuilder();

    sb.append(String.format("%s%25s\t", "abc","2"));
    sb.append(String.format("%s%25s\t", "asdf","4"));
    sb.append(String.format("%s%25s\t", "qwer xyz","5"));

    tv.setText(sb.toString());

Upvotes: 1

Related Questions