Skip to main content

How to align text within a TextView in Kotlin Android

How to align text within a TextView in Kotlin Android.

Here's a step-by-step tutorial on how to align text within a TextView in Kotlin Android:

Step 1: Create a new Android project in Kotlin and open the layout file where you want to align the text within a TextView.

Step 2: Add a TextView element to your layout file. You can do this by adding the following code to your XML layout file:

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="18sp" />

Step 3: Aligning text horizontally within a TextView:

  • To align the text to the left, add the following attribute to your TextView:
android:gravity="left"
  • To align the text to the center, add the following attribute to your TextView:
android:gravity="center"
  • To align the text to the right, add the following attribute to your TextView:
android:gravity="right"
  • To align the text to justify, add the following attribute to your TextView:
android:gravity="justify"

Step 4: Aligning text vertically within a TextView:

  • To align the text to the top, add the following attribute to your TextView:
android:gravity="top"
  • To align the text to the center vertically, add the following attribute to your TextView:
android:gravity="center_vertical"
  • To align the text to the bottom, add the following attribute to your TextView:
android:gravity="bottom"

Step 5: Combining horizontal and vertical alignment:

You can also combine horizontal and vertical alignment by using the | operator. For example, to align the text to the center horizontally and bottom vertically, you can use the following attribute:

android:gravity="center|bottom"

Step 6: Programmatically aligning text within a TextView:

If you want to align the text dynamically from your Kotlin code, you can use the gravity property of the TextView. Here's an example:

val textView = findViewById<TextView>(R.id.textView)
textView.gravity = Gravity.CENTER

In the above example, we are aligning the text to the center programmatically.

That's it! You have now learned how to align text within a TextView in Kotlin Android.