我知道标题有些令人困惑,我的问题是:我想使用 sleep(ms) 多次“暂停”我的程序(通过循环)并更改用户按下的几个按钮。我知道对 UI 的更改只能在主线程中进行,所以我想知道如何将此代码转换为异步任务。我还记得在某处读到异步任务只能调用一次?如果是这样,我可以研究哪些其他解决方案?
View.OnClickListener SimulateButtonHandler = new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int j=0;j<169;j++) //169 buttons to click
{
if(ClickedPoints[j]!=null) //how I keep track of which buttons has clicked
{ //clear button color
Drawable d2 = ClickedPoints[j].getBackground();
ClickedPoints[j].invalidateDrawable(d2);
d2.clearColorFilter();
}
}
Timer timer = new Timer();
for(int i=0;i<169;i++)
{
if(ClickedPoints[i]!=null)
{ //change the color after some time
Simulate(timer, i);
//clear color again
Drawable d2 = ClickedPoints[i].getBackground();
ClickedPoints[i].invalidateDrawable(d2);
d2.clearColorFilter();
}
}
}
};
public void Simulate(Timer timer, final int index)
{
timer.schedule(new TimerTask()
{
public void run() {
Sim(index);
}
}, 1000); //delay for some amount of time, then rehighlight the button
}
private void Sim(int i)
{
Drawable d1 = ClickedPoints[i].getBackground();
PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);
d1.setColorFilter(filter);
}