我还是Android的新手,目前我只是为了练习这个应用程序,但我遇到的一个问题就是让应用程序中的球改变颜色几秒钟左右,就像在那里3或6秒钟一样,问题是我使用的代码首先工作,但是在几秒延迟之后它又恢复到不同颜色而不等待。自从上次我没有得到我需要的答案以及因为它有点像它的基础知识,我觉得再次提出这个问题我感到愚蠢,并且可能没有像我想象的那么大。会不会感激任何帮助?
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius,ballY+ballRadius);
Handler handler = new Handler();
int rnd = (int)(Math.random() * 4);
switch(rnd){
case 0:handler.postDelayed(new Runnable(){
public void run(){
paint.setColor(Color.BLUE);
}
}, 3000);
break;
case 1: handler.postDelayed(new Runnable(){
public void run(){
paint.setColor(Color.RED);
}
}, 3000);
break;
case 2: handler.postDelayed(new Runnable(){
public void run(){
paint.setColor(Color.GREEN);
}
}, 3000);
break;
case 3:handler.postDelayed(new Runnable(){
public void run(){
paint.setColor(Color.YELLOW);
}
}, 3000);
break;
}
canvas.drawOval(ballBounds, paint);
update();
try{
Thread.sleep(20);
}catch(InterruptedException e){}
invalidate();
}
答案 0 :(得分:0)
将你的case语句放入1 runnable,但它需要比onDraw()更好的主页:
protected void onDraw(Canvas canvas) {
ballBounds.set(ballX - ballRadius, ballY - ballRadius, ballX + ballRadius, ballY + ballRadius);
Handler handler = new Handler();
int rnd = (int) (Math.random() * 4);
handler.postDelayed(new Runnable() {
public void run() {
switch (rnd) {
case 0:
paint.setColor(Color.BLUE);
break;
case 1:
paint.setColor(Color.RED);
break;
case 2:
paint.setColor(Color.GREEN);
break;
case 3:
paint.setColor(Color.YELLOW);
break;
}
}
}, 3000);
canvas.drawOval(ballBounds, paint);
update();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
invalidate();
}