Several Ways to Run Android AnimationDrawable
Category Programming Techniques
In project development, AnimationDrawable was used, but the animation did not run after calling start, which was puzzling. I searched on Google and made a record.
AnimationDrawable.start cannot be directly written in onClick, onStart, or onResume, as it is ineffective and cannot start the animation; it can only be written in event listeners, for example.
Here are several ways to run AnimationDrawable.
The first method: Start AnimationDrawable in an event listener. Here is an example where an event is generated when a view tree is about to be drawn.
AnimationDrawable ad;
ImageView iv = (ImageView) findViewById(R.id.animation_view);
iv.setBackgroundResource(R.drawable.animation);
ad = (AnimationDrawable) iv.getBackground();
iv.getViewTreeObserver().addOnPreDrawListener(opdl);
OnPreDrawListener opdl = new OnPreDrawListener(){
@Override
public boolean onPreDraw() {
ad.start();
return true; //Note the return value of this line
}
};
The second method to start the animation: (The animation will automatically run when the Activity starts)
ImageView image = (ImageView) findViewById(R.id.animation_view);
image.setBackgroundResource(R.anim.oldsheep_wait);
animationDrawable = (AnimationDrawable) image.getBackground();
RunAnim runAnim = new RunAnim();
runAnim.execute("");
class RunAnim extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params)
{
if (!animationDrawable.isRunning())
{
animationDrawable.stop();
animationDrawable.start();
}
return "";
}
}
The third method to start the animation: (The animation will automatically run when the Activity starts)
ImageView image = (ImageView) findViewById(R.id.animation_view);
image.setBackgroundResource(R.anim.oldsheep_wait);
animationDrawable = (AnimationDrawable) image.getBackground();
image.post(new Runnable()
{
@Override
public void run()
{
animationDrawable.start();
}
});
The fourth method to start the animation: (The animation will automatically run when the Activity starts)
ImageView image = (ImageView) findViewById(R.id.animation_view);
image.setBackgroundResource(R.anim.oldsheep_wait);
animationDrawable = (AnimationDrawable) image.getBackground();
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
animationDrawable.start();
super.onWindowFocusChanged(hasFocus);
}
**Click to Share Notes
-
-
-