Justifying text of TextView, in some cases, helps in a better presentation of data to the user. The text alignment on both left and right side makes paragraphs align with other elements and screen bezels.

Note: This feature is available from Android 8.0 only.

Kotlin Android TextView – Justify Text

In this Android Tutorial, we shall look into an example where we present with how to justify text in TextView through layout file and programmatically.

In this tutorial, we will learn how to justify text in TextView using layout file.

To justify text in TextView through layout file, add the following attribute key : value to the TextView.

<TextView
	android:id="@+id/tvJustified"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:justificationMode="inter_word"
	android:text="The text in this TextView is justified." />

To justify text in TextView programmatically, set the justification mode using the setter, as shown below :

textView.setJustificationMode(JUSTIFICATION_MODE_INTER_WORD);
Kotlin Android TextView - Justify Text
ADVERTISEMENT

Example 1 – Justify Text in TextView via Layout File

Create Android Project and replace activity_main.xml with the following code.

We have two TextViews in this layout file. The text in first TextView is justified, while that of second TextView is not justified.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvJustified"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:padding="20sp"
        android:justificationMode="inter_word"
        android:text="The text in this TextView is justified. This feature is introduced in Android version >= 8.0. The text in this TextView is justified. This feature is introduced in Android version >= 8.0.The text in this TextView is justified. This feature is introduced in Android version >= 8.0." />
    <TextView
        android:id="@+id/tvNotJustified"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:padding="20sp"
        android:text="The text in this TextView is not justified. No justification. The text in this TextView is not justified. No justification. The text in this TextView is not justified. No justification. " />

</LinearLayout>