ตัวอย่างนี้สาธิตวิธีสร้างแอนิเมชั่นการนับใน Android TextView
ขั้นตอนที่ 1 − สร้างโครงการใหม่ใน Android Studio ไปที่ไฟล์ ⇒ โครงการใหม่และกรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโครงการใหม่
ขั้นตอนที่ 2 − เพิ่มรหัสต่อไปนี้ใน res/layout/activity_main.xml
<?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://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:textColor = "#ff4500" android:layout_height = "wrap_content" android:singleLine = "true" /> </RelativeLayout>
ในโค้ดข้างต้น เราได้ใช้มุมมองข้อความเพื่อแสดงภาพเคลื่อนไหวการนับตั้งแต่ 0 ถึง 100
ขั้นตอนที่ 3 − เพิ่มรหัสต่อไปนี้ใน src/MainActivity.java
package com.example.andy.myapplication;
import android.animation.ValueAnimator;
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);
final TextView view = findViewById(R.id.text);
ValueAnimator animator = new ValueAnimator();
animator.setObjectValues(0, 100);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
view.setText(String.valueOf(animation.getAnimatedValue()));
}
});
animator.setDuration(10000); // here you set the duration of the anim
animator.start();
}
} ในการนับภาพเคลื่อนไหวให้ใช้รหัสต่อไปนี้ -
ValueAnimator animator = new ValueAnimator();
animator.setObjectValues(0, 100);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
view.setText(String.valueOf(animation.getAnimatedValue()));
}
});
animator.setDuration(10000);
animator.start(); ในโค้ดด้านบนนี้ จะเริ่มจาก 0 ถึง 100 โดยมีช่วงเวลา 1000ms
มาลองเรียกใช้แอปพลิเคชันของคุณกัน ฉันคิดว่าคุณได้เชื่อมต่ออุปกรณ์มือถือ Android จริงกับคอมพิวเตอร์ของคุณ ในการรันแอพจาก android studio ให้เปิดไฟล์กิจกรรมของโปรเจ็กต์แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณเป็นตัวเลือก แล้วตรวจสอบอุปกรณ์มือถือของคุณซึ่งจะแสดงหน้าจอเริ่มต้นของคุณ -


ในผลลัพธ์ข้างต้น จะเปลี่ยนข้อความด้วยการนับภาพเคลื่อนไหว