我有一个TextView在我的应用程序。我想让文本向右对齐。我试着补充道:

android:gravity="right"

但这对我没用。

我可能做错了什么?


当前回答

确保你没有使用android:layout_width="wrap_content"如果是这样,那么它将无法设置重力,因为你没有足够的空间来对齐文本。而是使用android:layout_width="fill_parent"

其他回答

一般来说,android:gravity="right"和android:layout_gravity="right"是不同的。

第一个参数会影响文本本身在视图中的位置,所以如果你想让它右对齐,那么layout_width=应该是"fill_parent"或"match_parent"。

第二个影响视图在其父视图中的位置,换句话说——在父视图中对齐对象本身(编辑框或文本视图)。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">

  <TextView
    android:id="@+id/tct_postpone_hour"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_gravity="center"
    android:gravity="center_vertical|center_horizontal"
    android:text="1"
    android:textSize="24dp" />
</RelativeLayout>

使一号在水平和垂直的中心对齐。

校正对齐已从Android API 26+支持TextView

<TextView ...
    ... android:justificationMode="inter_word" />

缺省情况下,value为none。

Android TextView文档

关于Android TextView的问题

确保你没有使用android:layout_width="wrap_content"如果是这样,那么它将无法设置重力,因为你没有足够的空间来对齐文本。而是使用android:layout_width="fill_parent"

以下是我的工作:

<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_alignParentEnd和android:textAlignment设置。