启动逐格动画动画

2023-09-12 00:37:11 作者:熬夜等死

我有开始一帧一帧动画的一个基本问题。

I have a basic question about starting a frame-by-frame animation.

当我致电 AnimationDrawable.start()从我的code法直接,它似乎并没有工作。

When I call the AnimationDrawable.start() method from my code directly, it doesn't seem to work.

public void onCreate(Bundle savedInstanceState) {  
   ...  
   mAnimation.start();  
   ...  
}

但是,如果我把此行的一个按钮的onclick()回调方法里面,pressing的布顿启动动画。

But if I put this line inside the onClick() callback method of a button, pressing the buton starts the animation.

为什么不能在code这条线的工作?

Why doesn't this line work in the code?

谢谢!

public class MyAnimation extends Activity {
@Override

public void onCreate(Bundle savedInstanceState) {

    AnimationDrawable mframeAnimation = null;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_animation);

    ImageView img = (ImageView) findViewById(R.id.imgMain);

    BitmapDrawable frame1 = (BitmapDrawable) getResources().getDrawable(
            R.drawable.splash1);
    BitmapDrawable frame2 = (BitmapDrawable) getResources().getDrawable(
            R.drawable.splash2);

    int reasonableDuration = 250;
    mframeAnimation = new AnimationDrawable();
    mframeAnimation.setOneShot(false);
    mframeAnimation.addFrame(frame1, reasonableDuration);
    mframeAnimation.addFrame(frame2, reasonableDuration);

    img.setBackgroundDrawable(mframeAnimation);

    mframeAnimation.setVisible(true, true);
    //If this line is inside onClick(...) method of a button, animation works!!
    mframeAnimation.start(); 
}

}

推荐答案

要注意的是不能将活动的onCreate()方法中调用的start()方法呼吁AnimationDrawable,因为AnimationDrawable还不是很重要的完全附着到该窗口。如果你想立即播放动画,而不需要互动,那么你可能想从onWindowFocusChanged()方法,在你的活动,这将被调用时,机器人将您的窗口成为焦点调用它。 在页面的最末端 http://developer.android.com/guide/topics/graphics/2d-graphics.html

It's important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the onWindowFocusChanged() method in your Activity, which will get called when Android brings your window into focus. Very end of the page http://developer.android.com/guide/topics/graphics/2d-graphics.html

 ImageView img = (ImageView)findViewById(R.id.some layout);
 AnimationDrawable frameAnimation =    (AnimationDrawable)img.getDrawable();
 frameAnimation.setCallback(img);
 frameAnimation.setVisible(true, true);
 frameAnimation.start();

和添加动画,你可以做这样的事情

and to add animation you can do something like

<animation-list   android:id="@+id/my_animation" android:oneshot="false" 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/frame1" android:duration="150" />
    <item android:drawable="@drawable/frame2" android:duration="150" />

 </animation-list>