如何在 Android TextView 中製作計數動畫?
此示例演示瞭如何在 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>
在上面的程式碼中,我們使用了 TextView 來顯示從 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,時間間隔為 1000 毫秒。
讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您專案中的一個活動檔案,然後單擊工具欄中的執行
圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -


在以上結果中,它將使用計數動畫更改文字。
點選 這裡 下載專案程式碼
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP