Java 用定时器改变圆的颜色
我只是想用定时器改变我画的圆圈的颜色。我已经在我的“Java 用定时器改变圆的颜色,java,android,timer,colors,Java,Android,Timer,Colors,我只是想用定时器改变我画的圆圈的颜色。我已经在我的“onCreate”方法中实现了以下代码: 方法switchColor()执行以下操作: public static void switchColor() { Random r = new Random(30); int random = r.nextInt(); if(random < 10) { p.setColor(Color.GREEN); } else if(rand
onCreate
”方法中实现了以下代码:
方法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);
}
}
publicstaticvoidswitchcolor(){
随机r=新随机(30);
int random=r.nextInt();
如果(随机<10){
p、 setColor(Color.GREEN);
}
否则如果(随机>10&&random<20){
p、 setColor(Color.BLUE);
}
否则{
p、 setColor(Color.RED);
}
}
当我运行此命令时,颜色保持为默认值
有人知道我是必须使用一个处理器还是一个不同的计时器模型吗
提前谢谢 您的
t.start()
在onCreate、onStart或onResume中丢失,具体取决于您想何时启动计时器 我现在找到了一个合适的解决方案:
//-------------------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------------------------
这工作非常好,我可以使用它为更多的定时器和不同的方法
谢谢大家 如果我在“t.scheduleAtFixedRate(..10001000);”之后直接输入“t.start();”,则会出现一个错误,说明-->对于类型计时器,方法start()未定义。您将问题的标题更改为“已解决”,请将其更改回,并在解决问题的答案旁边的勾号上单击。(如果这是你自己的答案,那没关系)谢谢你!你所要做的就是接受你的答案,你就完成了。(我想你得等一两个小时左右,我不记得了)
//-------------------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------------------------