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


当前回答

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

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

其他回答

试试看:

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

最简单的方法(令人惊讶的是,只有在评论中才会提到,所以我才会发布答案)是:

textview.setGravity(Gravity.CENTER)

在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
    android:id="@+id/txtSubject"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/subject"
    android:layout_margin="10dp"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge" />

对于线性布局:在XML中,使用以下内容

<TextView  
    android:id="@+id/textView1"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center_vertical|center_horizontal"
    android:text="Your Text goes here"
/>

要在运行时执行此操作,请在活动中使用类似的内容

TextView textView1 =(TextView)findViewById(R.id.texView1);
textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

对于相对布局:在XML中使用类似于

<TextView  
    android:id="@+id/textView1"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_centerInParent="true"
    android:text="Your Text goes here"
/>

要在运行时执行此操作,请在活动中使用类似的内容

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);