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

android:gravity="right"

但这对我没用。

我可能做错了什么?


当前回答

让我用WEB来解释重力概念,因为很多开发人员都知道它。

Android_layout_gravity行为浮动:左|右|顶部|底部

而android_gravity工作为text_align:中心|左|右

在Android中float是android_layout_gravity, text_align:是android_gravity。

android_layout_gravity相对于parent应用。如android_gravity应用于它的子内容或内部内容。

注意android_gravity只有当它的视图为match_parent时才有效(当它有空间居中时)。

其他回答

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

如果你能解决这个问题只有2个属性在你的TextView?

而不是需要改变你的线性布局属性,也许可以改变行为的线性布局子?

使用这种方式,你不需要改变线性布局的属性和行为,你只需要添加以下两个属性到你的目标TextView:

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

如果只改变你的目标来解决你的问题,而不是有机会在未来引起另一个问题,修改你的目标父亲,会更好吗?想想吧。

尝试添加android:gravity="center"到TextView

这应该可以达到目的

android:textAlignment=“textStart”

在我的情况下,我使用相对布局的一个emptyString

在纠结了一个小时之后。只有这个对我有用:

android:layout_toRightOf="@id/welcome"
android:layout_toEndOf="@id/welcome"
android:layout_alignBaseline="@id/welcome"

layout_toRightOf或layout_toEndOf都可以,但为了更好地支持它,我同时使用了它们。

更清楚地说:

这就是我想做的:

这是模拟器的输出

布局:

<TextView
    android:id="@+id/welcome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:text="Welcome "
    android:textSize="16sp" />
<TextView
    android:id="@+id/username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@id/welcome"
    android:layout_toRightOf="@id/welcome"
    android:text="@string/emptyString"
    android:textSize="16sp" />

注意:

android: layout_width = " wrap_content "的作品 不使用重力

以防还有人需要

android:gravity="end"