【问题标题】:Android TextView center textAndroid TextView 中心文本
【发布时间】:2014-06-23 13:20:16
【问题描述】:
这将允许文本视图水平居中。
<TextView
android:id="@+id/footer_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/footer_text" />
【问题讨论】:
标签:
android
textview
center
【解决方案1】:
只需像这样更改您的代码:
<TextView
android:id="@+id/footer_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textAlignment="center"
android:gravity="center"
android:text="@string/footer_text" />
【解决方案2】:
这是启动android时经常混淆的东西。 layout_gravity 确定视图在父视图中的对齐方式。 gravity 将视图内容集中在视图容器内。所以 layout_gravity 会让你的视图在你的布局中居中,而重力会让你的文本在它的视图中居中。
<TextView
android:id="@+id/footer_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/footer_text"
android:gravity="center" />
并且,假设您希望页脚拉伸布局的宽度,您可以这样做
<TextView
android:id="@+id/footer_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/footer_text"
android:gravity="center" />
只是为了更好地处理事情,但同样只有当您的视图拉伸整个布局宽度时。
【解决方案3】:
例如,只需将其包装成这样的 LinearLayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/footer_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Centered text example" />
</LinearLayout>