I am trying to make a little application that simulates the dice. I want the picture of the dice side randomly change 6 times after clicking the button. It should randomly change 6 times with 0,3 second delay after every random change. The problem is that it changes always only one time not six times as wished. I guess it will be just some trivial mistake but I could not find the right answer anywhere on the web. Here is the code and I thank u all in advance:
import java.util.Random;
import android.app.Activity;
import android.os.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class OneDice extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.onedicelayout);
final ImageView image = (ImageView) findViewById(R.id.OneDiceRollImage);
final int[] arrayOfDices = {
R.drawable.icon,
R.drawable.icon2,
R.drawable.icon3,
};
final Random rand = new Random();
View.OnClickListener rollOneDiceListener = new View.OnClickListener() {
@Override
public void onClick(View v){
int j = 0;
for(int i = 0; i<6; i++){
try {
j = rand.nextInt(3);
image.setImageResource(arrayOfDices[j]);
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Button oneDiceRollButton = (Button) findViewById(R.id.OneDiceRollButton);
oneDiceRollButton.setOnClickListener(rollOneDiceListener);
}
}
The
onClickmethod that circles through your dice images is a callback from the system.Meaning that the UI thread which calls the callback will only operate again when the method returns. And the system is not recording what your are doing internally, but just taking the last state (i.e. the last selected image).
You can solve this with an
AsyncTaskwhere you havedoInBackground()(pseudo code):And within
onProgressUpdate()you can then display the image