public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.rollDice:
Random ranNum = new Random();
int number = ranNum.nextInt(6) + 1;
diceNum.setText(""+number);
sum = sum + number;
for(i=0;i<8;i++){
for(j=0;j<8;j++){
int value =(Integer)buttons[i][j].getTag();
if(value==sum){
inew=i;
jnew=j;
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
//I want to insert a delay here
buttons[inew][jnew].setBackgroundColor(Color.WHITE);
break;
}
}
}
break;
}
}
我想在改变背景的命令之间设置一个延迟。我尝试使用线程计时器,并尝试使用run和catch。但它不起作用。我试过了
Thread timer = new Thread() {
public void run(){
try {
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
timer.start();
buttons[inew][jnew].setBackgroundColor(Color.WHITE);
但它只会变成黑色。
发布于 2013-04-08 16:06:56
尝试以下代码:
import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
}
}, 5000);
发布于 2015-01-27 19:30:00
你可以使用CountDownTimer
,它比任何其他发布的解决方案都要高效得多。您还可以使用其onTick(long)
方法生成有关时间间隔的定期通知
看一下这个显示倒计时30秒的示例
new CountDownTimer(30000, 1000) {
public void onFinish() {
// When timer is finished
// Execute your code here
}
public void onTick(long millisUntilFinished) {
// millisUntilFinished The amount of time until finished.
}
}.start();
发布于 2016-03-20 03:01:56
如果在应用程序中经常使用延迟,请使用此实用程序类
import android.os.Handler;
public class Utils {
// Delay mechanism
public interface DelayCallback{
void afterDelay();
}
public static void delay(int secs, final DelayCallback delayCallback){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
delayCallback.afterDelay();
}
}, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
}
}
用法:
// Call this method directly from java file
int secs = 2; // Delay in seconds
Utils.delay(secs, new Utils.DelayCallback() {
@Override
public void afterDelay() {
// Do something after delay
}
});
https://stackoverflow.com/questions/15874117
复制相似问题