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.




Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.