Android TextView không hỗ trợ justify text mặc định. Ví dụ này dùng RecyclerView với custom layout để hiển thị text justify (giả lập).
Lưu ý quan trọng
Từ API 26 (Android 8.0), TextView hỗ trợ android:justificationMode="inter_word" để justify text tự động. Ví dụ dưới dùng cách thủ công cho các API cũ.
Bước 1: Tạo dự án mới
Tạo dự án mới trong Android Studio.
Bước 2: Layout chính (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:scrollbars="none" />
</RelativeLayout>
Bước 3: Layout item (res/layout/list_item.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/song_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="@color/colorPrimaryDark" />
<TextView
android:id="@+id/song_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/song_title"
android:layout_alignStart="@id/song_title"
android:layout_marginTop="20dp"
android:textColor="#000" />
<TextView
android:id="@+id/song_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/song_year"
android:layout_alignParentEnd="true"
android:textColor="#000" />
</RelativeLayout>
Bước 4-8: Các file Java (Model, Adapter, ViewHolder, MainActivity)
Code tương tự ví dụ gốc, sử dụng RecyclerView.Adapter pattern chuẩn.
Để justify text thực sự trên API 26+:
<TextView
android:justificationMode="inter_word"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Văn bản dài sẽ được căn đều hai bên..." />
Chạy ứng dụng
RecyclerView hiển thị danh sách bài hát với layout tùy chỉnh.