如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?


当前回答

重新排列布局、图像或文本视图的位置属于对齐主题。因此,如果您想将图像src垂直放置在中间,应该使用下面编写的代码

android:layout_centerVertical="true"

和中心水平

android:layout_centerHorizontal="true"

否则,我认为我们也可以使用重力将每个元素放在父布局的中间,如android:gravity=“center”

其他回答

重新排列布局、图像或文本视图的位置属于对齐主题。因此,如果您想将图像src垂直放置在中间,应该使用下面编写的代码

android:layout_centerVertical="true"

和中心水平

android:layout_centerHorizontal="true"

否则,我认为我们也可以使用重力将每个元素放在父布局的中间,如android:gravity=“center”

如何将视图或其内容居中,例如TextView或Button水平和垂直?layout_gravity可用于定位视图位于其父视图的中心。当重力属性用于将视图的内容(例如“文本”)放置在视图的中心。

(1)水平居中文本视图

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
       android:orientation="vertical"
       android:layout_margin="10dp"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_gravity="center"
        android:background="#333"
        android:textColor="#fff"
        />

</LinearLayout>

(2)垂直居中文本视图

android:layout_gravity=“center_vertical”不起作用!!

要使TextView垂直居中,您需要做一个技巧。将TextView放置在RelativeLayout中,然后设置TextView属性android:layout_centerInParent=“true”

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
       android:orientation="vertical"
       android:layout_margin="10dp"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_centerInParent="true"
        android:layout_gravity="center_vertical"
        android:gravity="center"
        android:background="#333"
        android:textColor="#fff"
        />

</RelativeLayout>

(3)水平居中文本

android:gravity=“center_horizontal”

(4)水平和垂直居中文本

android:gravity=“center”这将使文本水平居中垂直地

<文本视图android:layout_width=“fill_parent”android:layout_height=“100dp”android:text=“Hello World!”android:gravity=“中心”android:background=“#333”android:textColor=“#fff”/>

实际上,我们可以通过排除fontPadding做得更好。

<TextView
  android layout_height="wrap_content"
  android layout_height="wrap_content"
  android:includeFontPadding="false"
  android:textAlignment="center"
/>

这是解决方案。

<TextView  
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:gravity="center"
       android:text="**Your String Value**" />

如果要将文本视图的宽度和高度设置为环绕内容,则必须根据父级支持的属性通过布局重力来管理其位置。否则你可以做。

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center"/>