如何在两行的TextView中使标题居中? [英] How to center a title in a TextView with 2 lines?

查看:130
本文介绍了如何在两行的TextView中使标题居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在TextView中居中放置文本以及如何在TextView父布局中居中放置文本,但是我要寻找的是如何使标题居中(文本居中,但第二行从同一点开始)。

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).

我要找的是这个

 |  Centered  |
 |  right!    |

或以下方式:

|    Center    |

不是这个(文字居中):

Not this (text centered):

 |     Too    |
 |  centered! |

或以下(以TextView为中心):

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?

推荐答案

使用 android:padding 属性添加一些填充,并为您的TextView添加 android:gravity = left

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

btw:还请注意,您始终可以在TextView中使用Html,即

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.

如果您想根据两行的长度(不知道哪一行更长)来居中文本,则实际上需要首先计算宽度,然后对填充进行相应的调整。由于每个字母的宽度不同(至少如果您使用DroidSans作为默认字体),您不能仅仅计算字母的数目就知道更长的单词。

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).

因此,请通过s.split()分割字符串,然后首先计算两行的宽度:

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.

这篇关于如何在两行的TextView中使标题居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆