问题
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?
回答1:
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.
回答2:
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.
回答3:
Would adding another TextView solve the problem? I mean, define two TextView's: one centered, and the other one right-aligned.
来源:https://stackoverflow.com/questions/3458718/how-to-center-a-title-in-a-textview-with-2-lines