gpt4 book ai didi

android - 如何每2秒生成一个圆圈

转载 作者:行者123 更新时间:2023-11-29 02:38:06 24 4
gpt4 key购买 nike

我想每 2 秒生成一个圆圈,在本例中为 5,但我做不到。该应用程序不会每 2 秒创建一个圆圈,而是等待 10 秒并将 5 个圆圈画在一起。我究竟做错了什么?谢谢。

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();
}

}
}

最佳答案

通过在 onDraw 中调用 run,您将暂停主线程。在主线程返回到框架中的事件循环之前,绘制不会出现。因此,你永远不应该在主线程上调用 sleep 或其他阻塞函数(基本上,你的应用程序会出现卡住)。如果你想在 2 秒内做某事,创建一个 Handler 并使用 postDelayed() 向它发送消息。然后让消息的可运行增加 View 设置为绘制的圆圈数,然后使 View 无效并在接下来的 2 秒内发布另一条消息。然后 View 应在其 onDraw 中绘制自己,检查要绘制的圆圈数的变量。

关于android - 如何每2秒生成一个圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45896879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com