需要做一个动画,睡眠1000然后做下一次睡眠1000等等,而不是它整个时间睡觉,然后一次播放所有动画。不知道我在做什么。
尝试计时器,在thread.sleep之前运行动画并使用A while循环而不是A for。
private void playLaunchAnimation()
{
final Animation animation = AnimationUtils.loadAnimation(this, R.anim.fadein);
for(int i=0; i < buttons.size();i++)
{
try {
Thread.sleep(1000);
buttons.get(i).startAnimation(animation);
} catch (Exception e){
/*
main declares that it throws InterruptedException. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException.
*/
}
}
}
嗨,请确保此代码可以帮助您
public static void main(String[] args) throws Exception {
for(int i=0; i < 10;i++) {
try {
Thread.sleep(1000);
System.out.println(i);
if(i==9) {
i=0;
}
} catch (Exception e){
System.out.println("error");
}
}
}
(答案假定在OP中并不完全清楚的Android。)
这有点像一种懒惰的方式 - 但也许会让你思考。让处理程序调用下一个处理程序以便只声明一个处理程序会更有趣 - 但这会更多一点。
private void playLaunchAnimation() {
final Animation animation = AnimationUtils.loadAnimation(this, R.anim.fadein);
for(int i=0; i < buttons.size();i++)
{
// Create a handler on the UI thread to execute after a delay.
// The delay is a function of loop index.
//
// It may be necessary to declare buttons final - but your
// OP did not list where it is defined.
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
buttons.get(i).startAnimation(animation);
}
}, ((i+1)*1000));
}
}
参考文献:
听起来你是从用户界面线程调用Thread.Sleep。这最终将导致整个用户界面在睡眠期间冻结。你真正想要的是从后台线程启动睡眠。
例如:
AsyncTask.execute(new Runnable() {
@Override
public void run() {
for(int i=0; i < buttons.size();i++)
{
try {
Thread.sleep(1000);
activity.runOnUiThread(new Runnable() {
buttons.get(i).startAnimation(animation);
});
} catch (Exception e){}
}
});
另一种使用后延迟的方法:
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
buttons.get(i).startAnimation(animation);
new android.os.Handler().postDelayed(this, 1000);
}
},
1000);