将文本中心与 android 对齐

新手上路,请多包涵

我知道这听起来很容易。我需要将文本放在中心,但是当文本太长时,它需要放在下面,但仍然在我的 xml 的中心对齐。

这是我的代码:

  <LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/showdescriptioncontenttitle"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:layout_centerHorizontal="true"
>
    <TextView
        android:id="@+id/showdescriptiontitle"
        android:text="Title"
        android:textSize="35dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />
</LinearLayout>

我放了 paddingTop 和 Bottom 因为我需要一些空间。 PS:我的代码更大;它在一个相对布局中。

原文由 Tsunaze 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 702
2 个回答

也将 android:gravity 参数在 TextView 设置为 center

为了测试不同布局参数的效果,我建议为每个元素使用不同的背景颜色,这样你就可以看到你的布局如何随着重力、layout_gravity 等参数的变化而变化。

原文由 peter.bartos 发布,翻译遵循 CC BY-SA 3.0 许可协议

用这种方式

txt.setGravity(Gravity.CENTER);

原文由 bhargavkumar040 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题