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


当前回答

在XML文件中使用。

布局文件

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

or:

在Java类中使用

TextView textView =(TextView)findViewById(R.id.texviewid);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

其他回答

用于相对布局

android:layout_centerInParent="true"

以及其他布局

android:gravity="center" 

在对TextView使用gravity时,API级别17中实现了另一种方法-

textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

不知道有什么区别,但它也起作用。但仅适用于API 17级或更高级别。

您可以这样做以使文本居中

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

这在与RelativeLayout一起使用时有效,其中布局的高度和宽度设置为wrap_content。

对于线性布局:在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);