I'm trying to do a whackamole type game. I have enabled ImageViews hole1 >hole 9. Calling swapFace() swaps the ImageView for a random period as I want to happen.
I want to start by calling start() which will, on onTick, call newPopup(). After a random interval of up to five seconds, newpopup() should call swapface().
Calling swapface on its own works exactly as it should, however calling start() results in no swapping. I have a feeling I'm missing something obvious and would appreciate a pointer.
private void start(){
CountDownTimer myCount = new CountDownTimer(60000, 800){
@Override
public void onTick(long millisUntilFinished) {
newPopup();
}
@Override
public void onFinish(){}
}; myCount.start();
}
private void newPopup(){
Random rand = new Random();
int w = rand.nextInt(5000);
CountDownTimer myCount3 = new CountDownTimer(w, 100) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
swapFace();
}
};
}
private void swapFace(){
Random rand = new Random();
int holeNo = rand.nextInt(9);
final ImageView x;
if (holeNo ==0){ x = (ImageView) findViewById(R.id.hole1);}
else if (holeNo ==1){ x = (ImageView) findViewById(R.id.hole2);}
else if (holeNo ==2){ x = (ImageView) findViewById(R.id.hole3);}
else if (holeNo ==3){ x = (ImageView) findViewById(R.id.hole4);}
else if (holeNo ==4){ x = (ImageView) findViewById(R.id.hole5);}
else if (holeNo ==5){ x = (ImageView) findViewById(R.id.hole6);}
else if (holeNo ==6){ x = (ImageView) findViewById(R.id.hole7);}
else if (holeNo ==7){ x = (ImageView) findViewById(R.id.hole8);}
else { x = (ImageView) findViewById(R.id.hole9);}
x.setImageResource(R.drawable.sad);
int timeUp = rand.nextInt(3000) + 500;
CountDownTimer myCount = new CountDownTimer(timeUp, 100){
@Override
public void onTick(long millisUntilFinished) {
}
}
}
I guess you want to prevent newPopup()
being called before its previous CountTimer instance finished. You can do it by using synchronized
, or making the tick in myCount
bigger than w
(5000) :
CountDownTimer myCount = new CountDownTimer(60000, 6000)
Or introduce a field
private newPopupRunning = false;
And use it :
private void newPopup(){
if(newPopupRunning) return;
newPopupRunning=true;
Random rand = new Random();
int w = rand.nextInt(5000);
CountDownTimer myCount3 = new CountDownTimer(w, 100) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
newPopupRunning=false;
swapFace();
}
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.