溫馨提示×

android animatorset 如何同步動畫

小樊
99
2024-11-27 08:23:44
欄目: 編程語言

在 Android 中,AnimatorSet 允許你組合多個動畫并控制它們的執行順序。要使 AnimatorSet 同步執行動畫,你可以使用以下方法:

  1. 將所有動畫添加到同一個 AnimatorSet 中。
  2. 使用 start() 方法啟動 AnimatorSet。

以下是一個簡單的示例,展示了如何使用 AnimatorSet 同步執行動畫:

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        view = findViewById(R.id.my_view);

        // 創建一個 AnimatorSet
        AnimatorSet animatorSet = new AnimatorSet();

        // 創建一個 ObjectAnimator,使 view 的寬度在 1 秒內變為 200px
        ObjectAnimator widthAnimator = ObjectAnimator.ofInt(view, "width", 100, 200);
        widthAnimator.setDuration(1000);

        // 創建另一個 ObjectAnimator,使 view 的透明度在 1 秒內變為 0.5
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(view, "alpha", 1f, 0.5f);
        alphaAnimator.setDuration(1000);

        // 將兩個動畫添加到 AnimatorSet 中
        animatorSet.playTogether(widthAnimator, alphaAnimator);

        // 設置動畫監聽器
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                System.out.println("動畫開始");
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                System.out.println("動畫結束");
            }
        });

        // 啟動 AnimatorSet
        animatorSet.start();
    }
}

在這個示例中,我們創建了一個 AnimatorSet,并向其中添加了兩個動畫:一個改變視圖寬度的動畫和一個改變視圖透明度的動畫。通過調用 playTogether() 方法,我們將這兩個動畫設置為同步執行。最后,我們使用 start() 方法啟動 AnimatorSet。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女