在安卓TextView中右对齐文本

250

我在我的应用程序中有一个TextView。我想要将其中的文本向右对齐。我尝试添加以下内容:

android:gravity="right"

但这对我不起作用。

我可能做错什么了?

21个回答

205

我认为你正在做这个:android:layout_width = "wrap_content"
如果是这样,请改成:android:layout_width = "match_parent"


2
@Bishan fill会填充剩余的空间,match会将其设置为父元素的宽度。 - Troy Cosentino
12
实际上,fill_parent和match_parent是相同的东西。之所以将名称更改为match_parent,是因为fill_parent这个术语似乎使人们感到困惑。 - Edward Falk
1
这个答案没有意义... - Ola Ström

170

android:gravity="right"一般与android:layout_gravity="right"不同。

第一个属性会影响视图中文本自身的位置,若需要右对齐,则layout_width=应该为"fill_parent""match_parent"

第二个属性则会影响视图在其父视图中的位置,换句话说,是将对象(编辑框或文本视图)在父视图中对齐。


102

更好的解决方案是最简单的方案,并且对你的代码行为做出的修改最少。

如果您只能在 TextView 上使用 2 个属性就能解决这个问题呢?

与其需要更改可能会改变 LinearLayout 子元素行为的 LinearLayout 属性,不如使用这种方法。

通过这种方式,您无需更改 LinearLayout 的属性和行为,只需将以下两个属性添加到目标 TextView 中:

android:gravity="right"
android:textAlignment="gravity"

将目标仅限于解决问题而不是修改目标本身,这样未来就不会出现新的问题。好好想想吧 :)


我收到一个错误,说在安卓包中找不到资源“textAlignment”的资源标识符。 - anu
你确定正在访问“TextView”属性吗?- 您可以从此处的参考中检查属性:http://developer.android.com/reference/android/view/View.html#attr_android:textAlignment - Paulo Roberto Rosa
4
textAlignment在API level 17(Android 4.2)中被添加。要使其生效,您的模拟器/设备需要运行4.2或更高版本。 - thanhtd
我尝试在Android 4.1.2中使用textAlignment属性,却收到了错误信息"找不到属性'textAlignment'对应的资源标识符"。我在这里找到了解决这个错误的答案https://dev59.com/TmIj5IYBdhLWcg3whFYI#20176191。你如何在4.0.3中使用它? - thanhtd

22

如果还有人需要的话

android:gravity="end"

那是干什么用的? - gumuruh
1
在LTR中,它将文本对齐到右侧,在RTL中则对齐到左侧。 - npk

21

android:layout_gravity 用于将文本视图与父布局对齐。 android:gravity 用于将文本视图中的文本对齐。

您确定要将文本视图中的文本向右对齐,还是想要将文本视图本身与父布局向右移动,或者两者都想实现?


我正在尝试将文本视图中的文本对齐到右侧。 - Bishan

15
以下代码片段:
android:textAlignment="textEnd"
android:layout_gravity="end"

对我来说运作得很好


9
android:gravity="right"

这基本上用于线性布局,所以您需要将TextView或EditText的宽度设置为

android:layout_width = "match_parent"

当您在相对布局中工作时,请使用

android:layout_alignParentRight="true"

8

请确保您没有使用 android:layout_width="wrap_content",否则无法设置重力,因为您没有足够的空间来对齐文本。取而代之,请使用 android:layout_width="fill_parent"


5

以下方法适用于我:

<TextView
    android:id="@+id/tv_username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sarah" />

<TextView
    android:id="@+id/tv_distance"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/tv_username"
    android:layout_alignParentEnd="true"
    android:layout_toEndOf="@+id/tv_username"
    android:text="San Marco"
    android:textAlignment="viewEnd" />

请注意第二个TextView的android:layout_alignParentEndandroid:textAlignment设置。

5
如果它在RelativeLayout中,您可以使用 android:layout_toRightOf="@id/"。
或者,如果您想要将其对齐到设备的右上角,则使用 android:layout_alignParentRight="true"。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接