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

青春壹個敷衍的年華 提交于 2020-01-24 01:25:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!