如何在android中制作随机帧动画?

Dev*_*man 5 random animation android frame

我有许多动画图像(帧),例如 image_1、image_2 和 image_3。我想在我的应用程序中使用这个动画图像,所以我尝试了

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false" >

    <item
        android:drawable="@drawable/image_1"
        android:duration="2000"/>
    <item
        android:drawable="@drawable/image_2"
        android:duration="50"/>
     <item
        android:drawable="@drawable/image_3"
        android:duration="50"/>

</animation-list>
Run Code Online (Sandbox Code Playgroud)

并将其设置为我的布局的背景

 public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if(hasFocus){

        final AnimationDrawable bgDrawable = (AnimationDrawable) ((LinearLayout) findViewById(R.id.animationLayout))
                .getBackground();
        ((LinearLayout) findViewById(R.id.animationLayout))
                .post(new Runnable() {

                    @Override
                    public void run() {
                        bgDrawable .start();
                    }
                });

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但这表明动画每次都以相同的顺序重复。random frame animation我想用这些图像制作一个。我该怎么做?

提前致谢

Sam*_*Rad 5

您可以创建一个新AnimationDrawable框架,而不是将 XML 绑定到它,只需手动创建框架并将它们添加到AnimationDrawable.

AnimationDrawable animationDrawable = new AnimationDrawable();

animationDrawable.addFrame("You BitmapDrawable for first frame", 2000);
animationDrawable.addFrame("You BitmapDrawable for second frame", 50);
animationDrawable.addFrame("You BitmapDrawable for third frame", 50);
Run Code Online (Sandbox Code Playgroud)

那里有一个很好的教程:

更新:

您可以有一个功能来重置AnimationDrawable并在您的特定时间随机填充它。这只是一个伪代码,因此请使用正确的语法根据您的需要进行调整:

public AnimationDrawable shuffleFrame(AnimationDrawable ad) {

    ad = null;
    ad = new AnimationDrawable();

    // Create your Drawable frames here
    ...

    // For each Drawable, pick a random one here and add the frame
    ...
    ad.addFrame(Randomly picked frame, duration);


    return ad;
}
Run Code Online (Sandbox Code Playgroud)

每次想要打乱帧时调用此函数。