Center Text in Android: TextView Alignment Guide

In Android layout files, you can center text by using the following method:

  1. Use the property android:gravity=”center” in a TextView to align the text in the center.
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="居中文本"
    android:gravity="center"/>
  1. Use the attribute android:layout_gravity=”center” in TextView to center the TextView in the parent layout.
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="居中文本"
    android:layout_gravity="center"/>
  1. If a TextView is included in a LinearLayout or RelativeLayout, you can use the properties android:layout_gravity=”center” or android:layout_centerHorizontal=”true” to center the TextView in the parent layout.
<LinearLayout
    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="居中文本"/>
</LinearLayout>

By using the above method, it is easy to achieve the effect of centering text in an Android application.

bannerAds