我希望按下按钮时发生两件事 1. 两张图片应该一遍又一遍地播放,给人一种生动而不静态的感觉。 2. 一个循环的声音。
当按钮未按下且手指抬起时 1.声音应该停止 2. 动画应该停止。
我现在使用的方法如代码所示:
package com.example.newanimation;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;
public class MainActivity extends Activity {
AnimationDrawable rocketAnimation;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView rocketImage = (ImageView) findViewById(R.id.imageView1);
rocketImage.setBackgroundResource(R.drawable.ball_animation);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
rocketAnimation.start();
return true;
}
return super.onTouchEvent(event);
}
}
XML 就像
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/ball01" android:duration="200" />
<item android:drawable="@drawable/ball02" android:duration="200" />
<item android:drawable="@drawable/ball03" android:duration="200" />
</animation-list>
我保留 android:oneshot="false"> 而不是 "true"因为我希望动画在按下按钮之前不停地来回播放,但我需要它在手指从按钮。
最佳答案
在 onTouchEvent()
中,检查 MotionEvent.ACTION_UP
以了解按钮已被取消按下。
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if(rocketAnimation.isRunning()){
rocketAnimation.stop();
}
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if(!rocketAnimation.isRunning()){
rocketAnimation.start();
}
}
return super.onTouchEvent(event);
}
关于java - 如何在未按下按钮时停止动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28379318/