我有一个关于图像视图更新的问题。基本上,我有一个按钮和一个骰子。我希望骰子旋转几次(模拟掷骰子) - 0.5 秒,最后停止。问题是:我只能看到最终结果。掷骰子模拟正在进行,但未显示更改(未刷新图像视图)。我认为这是我对应该实施的方式的错误理解。
我在一个简单的项目中隔离了问题,几行代码,你可以在这里下载它(如果你有时间玩它):http://dl.dropbox.com/u/26268461/vrtiKocku_eng。 rar
整个代码如下所示:
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;
}
}
}