I'm trying to show some imageviews after the user has clicked on a button then wait for some time for the user to see which was the correct button to click then hide it again. Something like this:
User clicks on button giving his answer
-> Score is updated and correct answer is shown to user by setting the visibility of the imageview to visible
-> wait a moment for the user to be able to see which was the correct answer
-> hide the imageview again and load a new question.
So far I have this:
private void gameLoop(){
new Thread(new Runnable() {
@Override
public void run() {
while (isRunning) {
if (time > 0) {
sleepmillis(1000);
time--;
runOnUiThread(new Runnable() {
@Override
public void run() {
textViewTime.setText(time + " sec.");
}
});
} else
finishGame();
}
}
}).start();
}
private void sleepmillis(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View view) {
int givenAnswer = -1;
switch (view.getId()) {
case R.id.buttonFirst:
case R.id.imageViewFirst:
givenAnswer = 0;
break;
case R.id.buttonSecond:
case R.id.imageViewSecond:
givenAnswer = 1;
break;
case R.id.buttonThird:
case R.id.imageViewThird:
givenAnswer = 2;
break;
case R.id.buttonFourth:
case R.id.imageViewFourth:
givenAnswer = 3;
break;
}
processAnswer(givenAnswer);
}
private void processAnswer(int givenAnswer){
if (givenAnswer == answers[4]){
score += 5000;
correctAnswersInARow++;
if (correctAnswersInARow == 3)
score += 15000;
if (correctAnswersInARow == 6){
score += 30000;
correctAnswersInARow = 0;
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
textViewScore.setText("Score: " + score);
}
});
showCorrectAnswer();
answers = gameData.getAnswers();
updateAnswers();
}
private void showCorrectAnswer(){
runOnUiThread(new Runnable() {
@Override
public void run() {
switch (answers[4]){
case 0:
ivCorrectFirst.setVisibility(View.VISIBLE);
break;
case 1:
ivCorrectSecond.setVisibility(View.VISIBLE);
break;
case 2:
ivCorrectThird.setVisibility(View.VISIBLE);
break;
case 3:
ivCorrectFourth.setVisibility(View.VISIBLE);
}
}
});
sleepmillis(400);
hideCorrectAnswers();
}
private void hideCorrectAnswers(){
runOnUiThread(new Runnable() {
@Override
public void run() {
ivCorrectFirst.setVisibility(View.INVISIBLE);
ivCorrectSecond.setVisibility(View.INVISIBLE);
ivCorrectThird.setVisibility(View.INVISIBLE);
ivCorrectFourth.setVisibility(View.INVISIBLE);
}
});
}
So the important part is in the showCorrectAnswer method, where I try to do what I explained here. Although the app waits 400 ms before loading a new question it doesn't show the correct answer.
ms is time duration in milliseconds.