Giới thiệu
Ví dụ này minh họa cách tạo hiệu ứng "máy gõ" (typewriter) - hiển thị văn bản từng ký tự một trong Android bằng custom Viewextends TextView.
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Custom Typewriter View (Typewriter.java)
package com.example.andy.myapplication;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.TextView;
public class Typewriter extends TextView {
private CharSequence mText;
private int mIndex;
private long mDelay = 500; // ms per character
public Typewriter(Context context) {
super(context);
}
public Typewriter(Context context, AttributeSet attrs) {
super(context, attrs);
}
private Handler mHandler = new Handler();
private Runnable characterAdder = new Runnable() {
@Override
public void run() {
setText(mText.subSequence(0, mIndex++));
if (mIndex <= mText.length()) {
mHandler.postDelayed(characterAdder, mDelay);
}
}
};
public void animateText(CharSequence text) {
mText = text;
mIndex = 0;
setText("");
mHandler.removeCallbacks(characterAdder);
mHandler.postDelayed(characterAdder, mDelay);
}
public void setCharacterDelay(long millis) {
mDelay = millis;
}
}
Bước 3: Sử dụng trong Activity (src/MainActivity.java)
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Typewriter writer = new Typewriter(this);
setContentView(writer);
writer.setCharacterDelay(150); // 150ms/ký tự
writer.animateText("Sample String... Sample String... Sample String...");
}
}
Giải thích cơ chế
Typewriter extends TextView: Kế thừa TextView, tự vẽ nội dungHandler + Runnable: Lặp lại việc thêm 1 ký tự sau delaymText.subSequence(0, mIndex++): Lấy substring từ đầu đến index hiện tạipostDelayed: Lên lịch chạy tiếp sau mDelay ms
Cách dùng trong XML Layout
Thay vì tạo bằng code, có thể khai báo trong XML:
<com.example.andy.myapplication.Typewriter
android:id="@+id/typewriter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />
Sau đó trong Activity: findViewById(R.id.typewriter).animateText("Nội dung...")
Chạy ứng dụng
Chạy app → Văn bản xuất hiện từng ký tự với độ trễ 150ms, tạo hiệu ứng như đang gõ real-time.