Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách tạo animation đếm số (count animation) cho TextView Android

Giới thiệu

Ví dụ này minh họa cách tạo hiệu ứng đếm số (0 → 100) cho TextView bằng ValueAnimator trong Android.

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:textColor="#FF4500"
        android:layout_height="wrap_content"
        android:singleLine="true" />

</RelativeLayout>

Bước 3: Animation đếm (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() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                view.setText(String.valueOf(animation.getAnimatedValue()));
            }
        });
        animator.setDuration(10000); // 10 giây
        animator.start();
    }
}

Giải thích ValueAnimator

ValueAnimator animator = new ValueAnimator();
animator.setObjectValues(0, 100); // Giá trị từ 0 đến 100
animator.addUpdateListener(animation -> 
    view.setText(String.valueOf(animation.getAnimatedValue())));
animator.setDuration(10000); // Thời gian animation (ms)
animator.start();
  • setObjectValues(0, 100): Khoảng giá trị animation (start, end)
  • addUpdateListener: Callback mỗi frame animation
  • getAnimatedValue(): Giá trị hiện tại (float/int tùy type)
  • setDuration(10000): Tổng thời gian 10 giây

Mở rộng: Định dạng số (thêm dấu phẩy, số thập phân)

animator.addUpdateListener(animation -> {
    float value = (float) animation.getAnimatedValue();
    view.setText(String.format("%,.1f", value)); // VD: 1,234.5
});

Chạy ứng dụng

Chạy app → TextView đếm từ 0 lên 100 trong 10 giây, cập nhật mượt mà mỗi frame.