Thread.Sleep() Android UI
Solution 1
This is similar to Waiting in android app
Try following the solution posted there and use the Timer Class
Solution 2
You must not sleep the UI thread as this would prevent android from delivering any other events to your activity's UI.
Instead, do something such as use a timer and have the timer's method use the run on ui thread facility to make the desired postponed change.
For robustness you may need to implement a state machine (either formally, or in effect) to keep track of what is supposed to be happening - you'll need to decide if the current delay should be aborted or enforced if another button is pushed, and make the state machine treat that appropriately.
Alin
Just started Android App Dev - Trying to learn as much as I can about programming in general!
Updated on June 15, 2022Comments
-
Alin almost 2 years
I'm working on a memory game for Android and I'm having a problem. When the user taps the second image - if the images are not the same I want the second image to show for 1, 2 seconds.
What I've tried is to sleep for 1-2 sec. the UI thread after the second image is activated - but this doesn't seem to work - the second image doesn't seem to show! (only the first images is showed)
Here's my code:
public void whenTapedImage(View v, int position) { i++; ImageView imgV=(ImageView)v; if(i%2!=0) { firstClick=position; imgV.setImageResource(im.images.get(firstClick)); } else { secondClick=position; imgV.setImageResource(im.images.get(secondClick)); try { Thread.currentThread().sleep(1000); if(!(im.images.get(firstClick).equals(im.images.get(secondClick)))) { Toast.makeText(easyGame.this, "Try Again!", Toast.LENGTH_SHORT).show(); im.notifyDataSetChanged(); gridview.setAdapter(im); gridview.invalidate(); aux=player1Turn; player1Turn=player2Turn; player2Turn=aux; } else{ done=done+2; ImageAdapter.keepVisibleViews.add(firstClick); ImageAdapter.keepVisibleViews.add(secondClick); if(player1Turn==true) { player1Score++; String score=Integer.toString(player1Score); score1.setText(score); } if(player2Turn==true) { player2Score++; String score=Integer.toString(player2Score); score2.setText(score); } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
What am I doing wrong?