i have a question regarding the refreshment of an imageview. Basically, I have a button and a dice. I want the dice to rotate a couple of times (to simulate a dice roll) – 0.5 sec, and finally to stop it. The problem is: I can just see the final result. The dice roll simulation is being done, but the change is not being shown (the imageview is not being refreshed). I think it’s my erroreneous understanding of the way this should be implemented.
I isolated the problem in a simple project, a couple of lines of code, you can download it here (in case you have the time to play with it): http://dl.dropbox.com/u/26268461/vrtiKocku_eng.rar
The whole code looks like this:
package com.viscode.vrtiKocku;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class VrtiKockuActivity extends Activity {
/** Called when the activity is first created. */
private final Handler mHandler = new Handler();
Random randomGenerator = new Random();
private ImageView dice1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dice1 = (ImageView)findViewById(R.id.imageView1);
mHandler.post(mRollDice);
}
private final Runnable mRollDice = new Runnable() {
public void run() {
Button buttonRollDice = (Button) findViewById(R.id.buttonRollDice);
buttonRollDice.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer rand, rollSimulationTimeLimit = 500, rollDuration = 100;;
//simulate dice roll for 500 ms, by 5 rolls at 100 ms
while (rollDuration < rollSimulationTimeLimit) {
rand = randomGenerator.nextInt(6) + 1;
postaviKocku(rand, dice1);
// wait and SHOW the simulated roll for 100 ms = rollDuration
try {
Thread.sleep(rollDuration);
} catch (InterruptedException e) {
e.printStackTrace();
}
rollDuration += rollDuration;
}
}
});
}
};
//this procedure sets the imageview to the proper image, based on the rolled number
private void postaviKocku(Integer rand, final ImageView dice) {
switch (rand) {
case 1:
dice.setImageDrawable(getResources().getDrawable(R.drawable.one_red));
break;
case 2:
dice.setImageDrawable(getResources().getDrawable(R.drawable.two_red));
break;
case 3:
dice.setImageDrawable(getResources().getDrawable(R.drawable.three_red));
break;
case 4:
dice.setImageDrawable(getResources().getDrawable(R.drawable.four_red));
break;
case 5:
dice.setImageDrawable(getResources().getDrawable(R.drawable.five_red));
break;
case 6:
dice.setImageDrawable(getResources().getDrawable(R.drawable.six_red));
break;
default:
break;
}
}
}
use Handler’s postDelayed instead of Threads..