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


当前回答

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

以上是使用.xml文件进行设置。

但我更喜欢java版本,因为如果需要,您也可以在运行状态下在代码中禁用它。下面是java代码。

textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

其他回答

我添加了xml片段,以使文本视图中心在线性和相对布局中对齐。

在线性布局中

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text In Center"
android:layout_gravity="center"
android:gravity="center"/>

在相对布局中

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text In Center"
android:layout_centerInParent= true/>

在RelativeLayout中,它会很好。

还有另一个按钮和任何你可以添加的东西。

以下内容对我很有用。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ff314859"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">
    <TextView 
        android:id="@+id/txt_logo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="your text here"
        android:textSize="30dp"
        android:gravity="center"/>

        ...other button or anything else...

</RelativeLayout>

应用重力:

TextView txtView = (TextView) findViewById(R.id.txtView);
txtView.setGravity(Gravity.CENTER_HORIZONTAL);

对于垂直:

txtView.setGravity(Gravity.CENTER_VERTICAL);

在XML中:

<TextView      
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center"
    android:text="@string/Hello_World"        
/>

你试过这样吗?

<TextView
android:id="+@id/txtVw"
android:gravity="center"
/>

TextView的高度和宽度是换行内容,然后文本视图中的文本始终居中,然后使用以下命令在父布局中居中:

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello.."/>
</RelativeLayout>

对于LinearLayout,代码也相同:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello.."/>
</LinearLayout>

从语法上讲,父级是RelativeLayout java代码,这在运行时使用类似的代码

TextView textView1 =(TextView)findViewById(R.id.texView1);
RelativeLayout.LayoutParams layoutParams = RelativeLayout.LayoutParams)textView1.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
textView1.setLayoutParams(layoutParams);