Reputation: 35
I'm new to android programming, right now for practice I'm trying to make an app where this ball bounces around the screen while changing from various colors such as red, green, blue, and yellow. So far I've managed to make the ball bounce but the issue I'm struggling with at the moment is having the ball change color every three or five seconds, this is so far what I have. This seems to work but only for the first time you start the activity after that it goes back to randomly changing colors without having to wait for three seconds to change, thanks and would appreciate any help.
@Override
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);
Upvotes: 0
Views: 276
Reputation: 585
Try something like this :
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius,ballY+ballRadius);
canvas.drawOval(ballBounds, paint);
}
public void startLoading(){
task = new TimerTask() {
@Override
public void run() {
int rnd = (int)(Math.random() * 4);
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;
}
postInvalidate();
}
};
timer = new Timer();
timer.schedule(task, 0, 3000);
}
Upvotes: 0
Reputation: 2415
Your problem is, that you start color changing in the onDraw. Everytime the ball is redrawn a new Runnable is added to the message queue. Each Runnable will only be executed after 3 seconds since it was added to the queue, but not since the message before it was executed.
That is why you get the delay, when you sart te activity, but then see quicker changes.
You could create acolor changing thread the has a build in delay between each new color calculation, though. That way you get the delay you want.
Upvotes: 1