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


当前回答

对于kotlin:

如果要将TextView从代码中居中:

textView.gravity = Gravity.CENTER

如果要水平居中:

textView.gravity = Gravity.CENTER_HORIZONTAL

或者,垂直居中:

textView.gravity = Gravity.CENTER_VERTICAL

其他回答

文本视图宽度和高度应为match_parent,并在文本视图属性中添加android:gravity=“center”。

android:layout_centerInParent="true"

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

您需要像这样设置文本视图重力(水平居中和垂直居中):

android:layout_centerHorizontal="true"   

android:layout_centerVertical="true"

动态使用:

textview.setGravity(Gravity.CENTER);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

对于线性布局:在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:gravity=“center”解决问题。