启动和停止动画(Starting and stopping animation)

2019-10-31 13:39发布

I am trying to figure out how on earth i can start and stop animation in my Android App.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    stopOneButton = (Button) findViewById(R.id.buttonStopOne);
    stopTwoButton = (Button) findViewById(R.id.buttonStopTwo);
    stopThreeButton = (Button) findViewById(R.id.buttonStopThree);
    startButton = (Button) findViewById(R.id.buttonStart);

    firstImage = (ImageView) findViewById(R.id.imageView1);

    firstImage.setBackgroundResource(R.drawable.spin_animation);

    frameAnimation = new AnimationDrawable();
    AnimationDrawable frameAnimation = (AnimationDrawable) firstImage.getBackground();
//  frameAnimation.start();

    firstImage.post(new Starter());

    stopOneButton.setOnClickListener(this);
    stopTwoButton.setOnClickListener(this);
    stopThreeButton.setOnClickListener(this);
    startButton.setOnClickListener(this);

}

class Starter implements Runnable {

    public void run() {
        frameAnimation.start();
    }

}

This is pretty much everything i have, and im starting from scratch without binding any buttons to the functionality, but the image is not spinning around at all.

This is my XML file for the drawable:

<?xml version="1.0" encoding="utf-8"?>
 <animation-list
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:oneshot="false">
    <item android:drawable="@drawable/image1" android:duration="500" />
    <item android:drawable="@drawable/image2" android:duration="500" />
    <item android:drawable="@drawable/image3" android:duration="500" />
    <item android:drawable="@drawable/image4" android:duration="500" />
 </animation-list>

More code for buttons:

@Override
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.buttonStopOne:

        break;

        case R.id.buttonStopTwo:
        break;

        case R.id.buttonStopThree:
        break;

        case R.id.buttonStart:
            frameAnimation.start();
        break;
    }
} 

Can anyone determine what im doing wrong?

Answer 1:

你必须动画应用到视图。 因此,假设firstImage()是要进行动画动画,来电firstImage.startAnimation(frameAnimation) 然后结束它调用firstImage.clearAnimation()

编辑:

好。 现在,我看到你在做什么,我猜Runnable你用永远不会被调用。 你可以尝试是等到看法已经完全膨胀,并在启动动画。 事情是这样的:

firstImage = (ImageView) findViewById(R.id.imageView1);
final AnimationDrawable frameAnimation = (AnimationDrawable) firstImage.getBackground();
ViewTreeObserver treeObserver = firstImage.getViewTreeObsver();
treeObvserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
   @Override
   public void onGlobalLayout(){
      frameAnimation.start();
   }
}

现在,我没有试过,但我在想什么会发生的情况是,当观点是完全充气可见,动画将开始。

边注: 这也是弄清楚当观点都有其尺寸的便捷方式。



文章来源: Starting and stopping animation