Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make random frame animation in android?

I have a number of animated images(frames) like image_1,image_2 and image_3.I want to use this animated image in my application so I tried

<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>

And set this as background of my layout

 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();
                    }
                });

        }
    }
}

But this shows the animation repeats every time in the same order. I want to make a random frame animation by using these images.How can i do this?

Thanks in Advance

like image 656
Devu Soman Avatar asked May 09 '13 08:05

Devu Soman


1 Answers

You can create a new AnimationDrawable and instead of binding the XML to it, just create frames manually and add them to 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);

There are a good tutorials out there:

  • KeyFrame Animations
  • Programmatic frame-by-frame animation example.

Update:

You can have a function to reset the AnimationDrawable and fill it up randomly at your specific time. This is just a pseudo code so adjust it for your need with correct syntax:

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;
}

Call this function every time you want to shuffle the frames.

like image 88
Sam R. Avatar answered Sep 28 '22 08:09

Sam R.