抱歉我的英文! :)
好的,我想每秒多次重复一次 - 比如这里:
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
现在,在里面我想生成1-3(包括)之间的随机数,如果它是3则做一些事情。
所以:
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Random rand = new Random();
int num = rand.nextInt(3)+1;
if(num==3){
// repeat action here.
}
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
在if语句中,我想重复其他操作(每5毫秒移动一次ImageView或类似的东西)。我该怎么做?谢谢。
答案 0 :(得分:0)
您可以使用CountDownTimer http://developer.android.com/reference/android/os/CountDownTimer.html 例如创建一个30秒(30000毫秒)的CountDownTimer并通知每秒(1000毫秒)
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//I get called every 1000ms
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
或只是一个处理程序。 http://developer.android.com/reference/android/os/Handler.html
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
//dostuff
handler.postDelayed(this,1000); //repeat after a second
}
});
对于动画,你应该看一下ObjectAnimator / ViewPropertyAnimation。