AnimationDrawable in Android problem
I am having a common problem doing animationdrawable in Android. I wanted to start an animation when the Activity starts, in the onCreate() method, but as many people have found, it doesn't work.
I have read lots of advice but nothing seems to work for me. If I start the animation in onClick() it works, it 开发者_Python百科requires user input, not starting immediately.
I tried starting it in a separate thread in onCreate() but that doesn't work either. I read here:
http://code.google.com/p/android/issues/detail?id=1818
but none of the advice worked, or I couldn't understand it.
Can someone help?
I've faced similar problems, and switched to overriding onWindowFocusChanged() instead of onCreate() and onResume():
public void onWindowFocusChanged(boolean hasFocus)
{
if (hasFocus)
{
animation.start();
}
else
{
animation.stop();
}
}
I think you have to start the animation after initialization of the view in question is complete. You should be able to do something like this:
final ImageView tweenImage = (ImageView) findViewById(R.id.imageView1);
tweenImage.setBackgroundResource(R.anim.cubicfacetween);
tweenImage.post(new Runnable() {
@Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) tweenImage.getBackground();
frameAnimation.start();
}
}
For setting src in imageView
((ImageView)findViewById(R.id.no_network_icon)).post(new Runnable() {
@Override
public void run() {
AnimationDrawable drawable = (AnimationDrawable) ((ImageView)findViewById(R.id.no_network_icon)).getDrawable();
drawable.start();
}
});
According to the link you provided you have to start the animation in a separate thread. In Java you do that by implementing the Runnable interface and start it with
Thread t = new Thread(new MyRunnable()); // MyRunnable inherits Runnable
t.start();
you can also write the code like this
new Thread(new Runnable() {
public void run(){
// some code that runs outside the ui thread.
}
}).start();
if you don't want to implement a whole new class. The latter is of course not that pretty but if you're making a small project it can be nice to know about.
Have you tried it this way or have you started your thread in another way?
Please also read Painless Threading that goes over what possibilities you have to perform actions outside the ui thread and how to post methods that runs on the ui thread from your own threads.
Edit: After reviewing the link you posted you have to wait a while before starting your thread, probably until onCreate is complete. According to the flowchart on this page you should be able to start your animation later, for instance in the onResume call. Have you tried starting it in a method called after onCreate?
You should only create things in onCreate, and "start" them in onStart or onResume.
精彩评论