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


当前回答

在任何视图的ConstraintLayout中:

(使用约束布局时,将高度和宽度设置为0,并让约束管理视图边界。)

<View
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

其他回答

如果您试图在TableLayout中的TableRow上居中文本,以下是我实现这一点的方法:

<TableRow android:id="@+id/rowName"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dip" >
    <TextView android:id="@+id/lblSomeLabel"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:gravity="center"
              android:layout_width="0dp"
              android:layout_weight="100"
              android:text="Your Text Here" />
</TableRow>

简单地,在XML文件中,将文本视图重心设置为中心:

<TextView
    android:gravity="center" />

这是解决方案。

<TextView  
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:gravity="center"
       android:text="**Your String Value**" />

您也可以使用以下组合:

android:gravity="left|center"

然后,如果文本视图宽度大于“fill_paint”,则文本仍将向左对齐(不居中,因为重力仅设置为“center”)。

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

android:layout_centerHorizontal="true"   

android:layout_centerVertical="true"

动态使用:

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