我创建了两个从runnable()实现的类。然后我多次调用它们,延迟时间不同。问题是,当我后来运行runnable()时,它需要知道postdelay被调用时变量的值,而不是实际运行时的值。
我认为我现在需要做的是在调用post delay时将变量传递到runnable()实例中。但是,我无论如何都无法弄清楚如何做到这一点。以下是参考源代码:
public void PlaySequence() throws InterruptedException{
for(int i = 0;i<level;i++){
mHandler.postDelayed(mToggleButtonOn, (i+1)*playbackOffTime);
mHandler.postDelayed(mToggleButtonOff, (i+1)*playbackOnTime);
currentProgIteration++;
}
currentProgIteration=0;
}
private Runnable mToggleButtonOn = new Runnable() {
public void run() {
try {
if(Sequence[currentProgIteration]==0){
ImageCard[0].setImageDrawable(getResources().getDrawable(R.drawable.yellow));
}
else if(Sequence[currentProgIteration]==1){
ImageCard[1].setImageDrawable(getResources().getDrawable(R.drawable.blue));
}
else if(Sequence[currentProgIteration]==2){
ImageCard[2].setImageDrawable(getResources().getDrawable(R.drawable.red));
}
else if(Sequence[currentProgIteration]==3){
ImageCard[3].setImageDrawable(getResources().getDrawable(R.drawable.green));
}
}
catch (IllegalStateException e) {
e.printStackTrace();
}
}
};
private Runnable mToggleButtonOff = new Runnable() {
public void run() {
Log.d("Info", "running Off currentProgIteration: "+currentProgIteration);
try {
if(Sequence[currentProgIteration]==0){
ImageCard[0].setImageDrawable(getResources().getDrawable(R.drawable.darkyellow));
}
else if(Sequence[currentProgIteration]==1){
ImageCard[1].setImageDrawable(getResources().getDrawable(R.drawable.darkblue));
}
else if(Sequence[currentProgIteration]==2){
ImageCard[2].setImageDrawable(getResources().getDrawable(R.drawable.darkred));
}
else if(Sequence[currentProgIteration]==3){
ImageCard[3].setImageDrawable(getResources().getDrawable(R.drawable.darkgreen));
}
}
catch (IllegalStateException e) {
e.printStackTrace();
}
}
};
这些可运行程序正在使用全局变量currentProgIteration,但是当它们在延迟后运行时,该变量已经被重置为0。
感谢任何建议。