How to center the text in an Android TextView?

In Android, there are two ways to center the text of a TextView.

  1. Setting properties: In an XML layout file, you can center text by setting the attribute android:gravity=”center” for a TextView. For example:
  2. Setting using code: In Java code, you can use the setTextAlignment() method to center the text in a TextView. For example:
  3. Find the TextView element with the ID “textView”, set its text to “Hello World!” and align the text to the center.

Note: The setTextAlignment() method requires a minimum API level of 17 (Android 4.2) or higher. If your application needs to support devices below API 17, you may consider using attribute-based settings instead.

bannerAds