Center Align TextView Android Horizontally or Vertically


To align a text in a TextView in android,

Layout xml file

Add android:gravity="center_horizontal" to the TextView to make the text center aligned horizontally. For center vertical alignment use android:gravity="center_vertical"

<LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView1"
                android:textSize="22sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:text="@string/my_text" />
            
    </LinearLayout>

In Java Code (Programmatically)

You can also achieve the same in java code,

myText.setGravity(Gravity.CENTER);

Gravity.CENTER: Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.

myText.setGravity(Gravity.CENTER_HORIZONTAL);

Gravity.CENTER_HORIZONTAL: Place the object in the horizontal center of its container, not changing its size.

myText.setGravity(Gravity.CENTER_VERTICAL);

Gravity.CENTER_VERTICAL: Place the object in the vertical center of its container, not changing its size.


Top Hashtags:

Advertisements

Advertisements




Advertisements