Search code examples
androidtextviewspannablestring

How to align colons in a textview in android?


I am trying to display strings on textview in android app I have following strings

String Fruityellow = " Mango" ;
String Fruitred = " Apple" ;
String Fruitgreen = " Guava" ;
String Fruitpink = " Pomegranate" ;

So i append them and print them on textview
output_display = "Fruityellow     :" + Fruityellow + "\r\n" + 
         "Fruitred        :" + Fruitred + "\r\n" +
         "Fruitgreen      :" + Fruitgreen + "\r\n" +
         "Fruitpink       :" + Fruitpink + "\r\n" );

text_view.settext(output);

But the display shows vertically misaligned colons .Why ?

So i used spannable string to keep colons at center

SpannableString span_colon      = new SpannableString(":");
span_colon.setSpan((new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER)), 0, span_colon.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

spanned total_display = (Spanned)TextUtils.concat("Fruityellow",span_colon,Fruityellow,
"\r\nFruitred",span_colon,Fruitred,
"\r\nFruitgreen",span_color,Fruitgreen,
"\r\nFruitpink",span_color,Fruitpink);

 text_view.settext(total_display );

Current ouptut is:

Fruityellow:Mango
Fruitred:Apple
Fruitgreen:guava
Fruitpink:Pomegranate

Expected output is :

Fruityellow     : Mango
Fruitred        : Apple
Fruitgreen      : guava
Fruitpink       : Pomegranate

if i just print span_colon it correctly comes in center of screen

How to get colon in center of screen in textview ? colon is not needed to be in center but should be vertically aligned .


Solution

  • Your way to use space is not working because the font used for the TextView has different width and size for each character, including space itself. If you can add android:fontFamily="monospace" to the xml, then it will show space as you expected, but maybe it's not the font you are expecting for your TextView.