views:

50

answers:

3

I know how to center the text in the TextView and how to center the TextView inside its parent layout, but what I'm looking for is how to center a title (text centered but second line starting at the same point).

What I'm looking for is this:

 |  Centered  |
 |  right!    |

or this:

|    Center    |

Not this (text centered):

 |     Too    |
 |  centered! |

or this (TextView centered):

 |Centered    |
 |wrong!      |

or this (with padding and left):

|  |Also     |  |
|  |wrong!   |  |

Did anyone understad this? Is it possible to do this without coding the String itself?

A: 

Use the android:padding attribute to add some padding, and android:gravity="left" for your TextView.

btw: also note you can always use Html in your TextView, i.e.

txtView.setText( Html.fromHtml("Centered<br/>right!") );

but you might not need it if the button width is set in a way that it will break the word automatically.

If you want to center the text depending on the lenghts of the two lines (of which you don't know which one is longer), you will actually need to calculate the width first, then do the adjustment to the padding accordingly. You cannot just count the numbers of letters to know the longer word, since each letter has a different width (at least if you use DroidSans as the default font).

Therefore, split your string via s.split(" ") and then calculate the width of both lines first:

txtText.getPaint().measureText(s[0])
txtText.getPaint().measureText(s[1])

and then depending on the return value, set the left padding of the text view accordingly.

Mathias Lin
If I use android:padding and android:gravity="left" then short titles will not be centered. But I guess I could live with that...
ciffa
On second thought. This will not work. I want the width to be dynamic so the center of the longest line is centered above a picture. I might not be explaining this properly. :/
ciffa
ok, I get what you mean. see my edited reply...
Mathias Lin
I understand now. Thanks for the help.
ciffa
A: 

Would adding another TextView solve the problem? I mean, define two TextView's: one centered, and the other one right-aligned.

Asahi
A: 

Set layout_width to fill_parent and android:gravity (not layout_gravity) to center. This will center each line of text individually in the textview, which is the same size as the parent.

aschmack
Not really what I had in mind but a good alternative.
ciffa