How to get a string in a specific format in android

Suppose I want to print “Item” and its “price” in a specific format, for example

abc           2
asdf          4
qwer xyz      5

And 2, 4, 5 should be in the same column.

For this 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 conclusion -

abc             2
asdf             4
qwer xyz             5

I want "abc" and after 25 spaces I want "5", but it doesn’t count 25 spaces from abc from the beginning

+4
source share
2 answers

You messed 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

This minus sign in front of 25 means invert text alignment. The final step is to use a monospace font. You can achieve this with this line:

tv.setTypeface(Typeface.MONOSPACE);
+5
source

You can use the tab on each line. Hope this works.

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());
+1

Source: https://habr.com/ru/post/1525182/


All Articles