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


当前回答

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

其他回答

如果使用TableLayout,请确保将TableRows的重心也设置为中心。否则它将无法工作。至少在我将TableRow的重心设置为中心之前,它没有对我起作用。

例如,如下所示:

<TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center">        
    <TextView android:text="@string/chf" android:id="@+id/tv_chf" android:layout_weight="2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center"></TextView>        
</TableRow>

应用重力:

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.setGravity(Gravity.CENTER)

对于线性布局:在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);
android:layout_centerInParent="true"

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