gpt4 book ai didi

java - 用计时器改变圆圈的颜色

转载 作者:行者123 更新时间:2023-11-30 10:57:38 25 4
gpt4 key购买 nike

我只是想用计时器改变我绘制的圆圈的颜色。我在我的“onCreate”方法中实现了以下代码:

     Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {

@Override
public void run() {
runOnUiThread(new Runnable() {

@Override
public void run() {
Drawing.switchColor();
}
});
}
},
1000,
1000);

switchColor() 方法执行以下操作:

    public static void switchColor() {
Random r = new Random(30);
int random = r.nextInt();
if(random < 10) {
p.setColor(Color.GREEN);
}
else if(random >10 && random < 20) {
p.setColor(Color.BLUE);
}
else {
p.setColor(Color.RED);
}
}

当我运行它时,颜色保持默认。

有谁知道我是否必须在内部或不同的计时器模型中使用处理程序?

提前致谢!

最佳答案

我现在找到了一个合适的解决方案:

//-------------------Part 1 of AddCircleTimer------------------------
//Declare the timerAddCircle
timerAddCircle = new Timer();
timerAddCircle.schedule(new TimerTask() {
@Override
public void run() {
TimerMethodAddCircle();
}
}, 1000, 1000);

//-------------------Part 2 of AddCircleTimer------------------------
private void TimerMethodAddCircle()
{
//This method is called directly by the timer and runs in the same thread as the timer.
//We call the method that will work with the UI through the runOnUiThread method.
this.runOnUiThread(Timer_Add);
}

private Runnable Timer_Add = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
Drawing.addCircle();
d.invalidate();
}
};
//-------------------END Part 2 of AddCircleTimer------------------------

这工作得很好,我可以将它用于更多的计时器和不同的方法!

感谢大家!

关于java - 用计时器改变圆圈的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32538611/

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