【发布时间】:2015-04-08 18:37:39
【问题描述】:
我正在尝试连续为 4 个图像设置动画,当我收到一条发送广播意图的新 GCM 消息时切换动画。我将展示前 2 个的代码,以及出了什么问题。基本上在两个命令之间(案例 0 与案例 1),我需要能够停止第一个可运行,然后启动第二个。我尝试通过设置来做到这一点
isRunning = false;
但这不起作用。我在想,如果我继续破解,我可能会做对,但我想知道正确的做法是什么。
public void startAnimatedBackground(Integer num) {
isRunning = false;
ImageSwitcher imageSwitcher = null;
aniIn = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
aniOut = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);
aniIn.setDuration(500);
aniOut.setDuration(500);
switch (num) {
case 0:
imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher_accept);
break;
case 1:
imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher_on_way);
break;
default:
break;
}
imageSwitcher.setInAnimation(aniIn);
imageSwitcher.setOutAnimation(aniOut);
imageSwitcher.setFactory(this);
imageSwitcher.setImageResource(images[0]);
isRunning = true;
final Handler handler = new Handler();
final ImageSwitcher finalImageSwitcher = imageSwitcher;
Runnable runnable = new Runnable() {
@Override
public void run() {
if (isRunning) {
System.out.println("Running.."+finalImageSwitcher+index);
index++;
index = index % images.length;
finalImageSwitcher.setImageResource(images[index]);
handler.postDelayed(this, interval);
}
}
};
handler.postDelayed(runnable, interval);
}
这是一开始发生的事情,而且是正确的。我得到一个闪烁的图像。
...app:id/switcher_accept}1 ...应用程序:id/switcher_accept}0 ...应用程序:id/switcher_accept}1 ...应用程序:id/switcher_accept}0 ...app:id/switcher_accept}1
case 2 运行后,运行过程是这样的。如您所见,两者都在运行,并且没有发生任何预期的行为。我想要的是第二个(switcher_on_way)像以前一样运行。我希望我的 isRunning=false;代码会让这种情况发生,但显然不是。
...app:id/switcher_on_way}0 ...应用程序:id/switcher_accept}1 ...应用程序:id/switcher_on_way}0 ...应用程序:id/switcher_accept}1 ...应用程序:id/switcher_on_way}0 ...app:id/switcher_accept}1
【问题讨论】:
标签: java android android-handler