开发者

How to center a title in a TextView with 2 lines?

I know how to center the text in the TextView and how to cent开发者_C百科er 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?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜