Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีสร้างแอนิเมชั่นแสดงข้อความทีละตัวอักษรใน Android


ตัวอย่าง: การแสดงข้อความทีละตัวอักษร (Typewriter Effect)

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็น

ขั้นตอนที่ 2: เขียนโค้ด Java (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);
        writer.animateText("Sample String...Sample String...Sample String...");
    }
}

ในโค้ดข้างต้น เราใช้ Custom Class Typewriter เป็น View หลักของ Activity

สร้าง Class Typewriter (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 = 5000;

    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;
    }
}

การทำงานของ Typewriter Class

  • สืบทอดมาจาก TextView
  • ใช้ Handler และ Runnable เพื่อเพิ่มตัวอักษรทีละตัว
  • mDelay ควบคุมความเร็ว (มิลลิวินาทีต่อตัวอักษร)
  • เมธอด animateText() เริ่มต้นการแสดงผล

การทดสอบแอปพลิเคชัน

เชื่อมต่ออุปกรณ์ Android จริง ใน Android Studio คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอ

วิธีสร้างแอนิเมชั่นแสดงข้อความทีละตัวอักษรใน Android

วิธีสร้างแอนิเมชั่นแสดงข้อความทีละตัวอักษรใน Android

วิธีสร้างแอนิเมชั่นแสดงข้อความทีละตัวอักษรใน Android

ข้อความจะแสดงทีละตัวอักษร โดยค่าเริ่มต้นหน่วง 5000ms ต่อตัว (ใน MainActivity ตั้งเป็น 150ms)