0
\$\begingroup\$

I want to generate circles every 2 seconds, in this case 5 but I can't get it. Instead of creating a circle every 2 seconds, the app wait 10 seconds and draw the 5 circles together. What am I doing wrong?

public class Juego extends SurfaceView{

boolean isItOK = false;

Paint paint;
int CantidadDeEsferas = 5;
int radio, alto, ancho;

public Juego(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);

    paint = new Paint();
}

public void onDraw(Canvas canvas){

    paint.setColor(Color.WHITE);
    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);

    paint.setColor(Color.BLACK);

    for (int i=0; i<CantidadDeEsferas; i++) {

        Random r = new Random();
        alto = r.nextInt(canvas.getHeight());
        ancho = r.nextInt(canvas.getWidth());
        radio = r.nextInt(101 - 50) + 50;
        canvas.drawCircle(ancho, alto, radio, paint);
        run();
        isItOK = true;
    }
}

public void run(){
    while (isItOK){
        try
        {
            Thread.sleep(2000);
            isItOK = false;
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

    }
}

}

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

Don't sleep in onDraw.

Instead use a timer of some kind to trigger creation of another circle:

List<Circle> circles = new ArrayList<Circle>();

private static class Circle{
    int radio, alto, ancho;
}
Handler handler;
public void generateCircle(){

    Circle c = new Circle();
    c.alto = r.nextInt(canvas.getHeight());
    c.ancho = r.nextInt(canvas.getWidth());
    c.radio = r.nextInt(101 - 50) + 50;
    invalidate();
    if(circles.size() < 5) handler.postDelayed(new Runnable(){public void run(){generateCircle();}}, 2000);
}

public void onDraw(Canvas canvas){

    paint.setColor(Color.WHITE);
    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);

    paint.setColor(Color.BLACK);

    for (int i=0; i<circles.size(); i++) {
        Circle c = circles.get(i);
        canvas.drawCircle(c.ancho, c.alto, c.radio, paint);
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Hi, thanks for the answer. The "handler.postDelayed" says cannot resolve method postDelayed. And the method "generateCircle()" its never used \$\endgroup\$ Commented Aug 24, 2017 at 16:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .