Sunday, November 1, 2009

AnimationDrawable problem

You may encounter a big problem when playing with an AnimationDrawable object in Android: it won't start! Actually it will remain blocked on the first frame and it will confuse you why it didn't start moving. So you may lose this way a couple of hours just trying to find where is the problem. The code seems to be okay, you did something like this:

public class Present extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout l = (LinearLayout) findViewById(R.id.main);
AnimationDrawable d = (AnimationDrawable) getResources().getDrawable(R.drawable.myanimation);
d.setBackgroundDrawable(d);
d.start();
}
}

I saw a couple of people complaining on forums but no one answered to their problem.
Now the catch is that no UI object is created until the onCreate function call is terminated. I assume that android internal framework doesn't start rendering the UI after setContentView, but it waits for the onCreate to terminate then it starts showing all the graphic elements. So what you need to do is call "d.start()" after we get past onCreate. Though I'm not saying it's the best solution, here is a little workaround:

public class Present extends Activity{
class AnimationStarterThread extends Thread{
private AnimationDrawable myAnimation;
public AnimationStarterThread(AnimationDrawable ad)
{
myAnimation = ad;
}
public void run()
{
ad.wait();
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
ad.start();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout l = (LinearLayout) findViewById(R.id.main);
AnimationDrawable d = (AnimationDrawable) getResources().getDrawable(R.drawable.myanimation);
d.setBackgroundDrawable(d);
AnimationStarterThread ast = new AnimationStarterThread();
ast.start();

//do other initialisations

ad.notify();
}
}


It's very far from an elegant solution. If I'll find a way to hook the event of UI post-initialization(this is the way to do it) I'll post an update.

No comments:

Post a Comment