繁体   English   中英

开始和停止动画

[英]Starting and stopping animation

我正在尝试弄清我如何在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();
    }

}

这几乎是我所拥有的一切,即时通讯是从零开始的,没有将任何按钮绑定到功能,但是图像根本没有旋转。

这是我的可绘制XML文件:

<?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>

按钮的更多代码:

@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;
    }
} 

谁能确定我做错了什么?

您必须将动画应用于视图。 因此,假设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();
   }
}

现在,我还没有尝试过,但是我想的是,当视图完全膨胀并可见时,动画将开始。

旁注: 这也是找出视图何时具有尺寸的便捷方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM