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


当前回答

如果您试图在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>

其他回答

让我们在屏幕中显示全文视图

 <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Hello World!"
    android:gravity="center"
    />

让我们说相对布局中的文本视图(未满)

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:layout_centerInParent=true
    />

假设Linear_layout中的Textview(未满)

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:layout_gravity="centre"
    />

TextView的高度和宽度是换行内容,然后文本视图中的文本始终居中,然后使用以下命令在父布局中居中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello.."/>
</RelativeLayout>

对于LinearLayout,代码也相同:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello.."/>
</LinearLayout>

从语法上讲,父级是RelativeLayout java代码,这在运行时使用类似的代码

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

对于那些想知道如何在其TextView元素中垂直居中,同时将其保持在左侧(水平)的人:

android:gravity="center"
android:textAlignment="viewStart"

试试这种方法,它会奏效的

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center">
  
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"/>

</LinearLayout>

你试过这样吗?

<TextView
android:id="+@id/txtVw"
android:gravity="center"
/>