如何在触摸时启动动画并在再次触摸后停止?

时间:2011-12-29 23:47:39

标签: android eclipse touch

我有一个我制作的Android应用程序,一切正常,但我想添加一个代码,一旦我再次触摸屏幕就会停止动画。正如您在代码中看到的那样,我开始动画,但我只能通过退出程序来停止它,我希望能够再次触摸屏幕以停止动画和声音播放。

谢谢。

import android.app.Activity;
import android.os.Bundle;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.view.MotionEvent;
import android.widget.ImageView;



public class WigleActivity extends Activity {
/** Called when the activity is first created. */

MediaPlayer mp;
AnimationDrawable animation;

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

    mp = MediaPlayer.create(this, R.raw.sexy);

    ImageView imageView1 = (ImageView)findViewById(R.id.imageView1);
    imageView1.setBackgroundResource(R.anim.wanim);
    animation = (AnimationDrawable) imageView1.getBackground();       
}

protected void onPause() {
    super.onPause();

    mp.release();
    finish();
}

public boolean onTouchEvent (MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
    mp.start();
    animation.start();
    return true;

}
return super.onTouchEvent(event);
}

}

1 个答案:

答案 0 :(得分:1)

将onTouch代码更改为以下内容:

public boolean onTouchEvent (MotionEvent event) {
  if (event.getAction() == MotionEvent.ACTION_DOWN) {
    if (animation.isRunning()) {
       mp.stop();
       animation.stop();
    } else {
       mp.start();
       animation.start();
    }
    return true;

  }
  return super.onTouchEvent(event);
}