Giới thiệu
Ví dụ này minh họa cách tạo hiệu ứng văn bản chạy (marquee) trong TextView Android - văn bản dài tự động cuộn ngang khi không đủ chỗ hiển thị.
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:textSize="20dp"
android:textAlignment="center"
android:layout_width="match_parent"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:textColor="#FF4500"
android:text="Ví dụ marquee: Văn bản dài sẽ tự động cuộn từ phải sang trái liên tục"
android:layout_height="wrap_content"
android:singleLine="true" />
</RelativeLayout>
Giải thích thuộc tính marquee
android:ellipsize="marquee" android:fadingEdge="horizontal" android:marqueeRepeatLimit="marquee_forever" android:scrollHorizontally="true" android:singleLine="true"
ellipsize="marquee": Kích hoạt chế độ cuộnsingleLine="true": Bắt buộc - marquee chỉ hoạt động trên 1 dòngmarqueeRepeatLimit="marquee_forever": Cuộn vô hạnfadingEdge="horizontal": Mờ 2 đầu tạo hiệu ứng mượtscrollHorizontally="true": Cho phép cuộn ngang
Bước 3: Kích hoạt (src/MainActivity.java)
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = findViewById(R.id.text);
txt.setSelected(true); // QUAN TRỌNG: Marquee chỉ chạy khi selected=true
}
}
Chạy ứng dụng
Chạy app → TextView cuộn văn bản từ phải sang trái liên tục, lặp lại vô hạn.
Mẹo: Marquee cho TextView trong ListView/RecyclerView
Trong Adapter, gọi holder.textView.setSelected(true) trong onBindViewHolder.