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.

Advertisements
Try Out Code2care Dev Tools:

Advertisements



#Android #Java #Linux #Microsoft #Google #Python #MacOS #Notepad++ #Microsoft Teams #CSS #PHP #SharePoint #Html #Linux #C-Program #Bootstrap #jQuery #Sublime #Android-Studio #Facebook #Eclipse #WhatsApp #News #MySQL #Json #HowTos #JavaScript #FTP #S3


Advertisements


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, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency