S.B*_*oda 3 java android for-loop thread-sleep
我想知道为什么我仍然无法想办法做到这一点.虽然看起来很简单,但我花了整整一天的时间.但不能这样做.
我有一组骰子图像.1.png,2.png,....和6.png.我的布局中有一个ImageView.那是,
ImageView dice = (ImageView) findViewById(R.id.imageViewrollingdiceOne);
Run Code Online (Sandbox Code Playgroud)
在这里,我想快速更改此imageView以查看使用上述6个图像的某种视觉/动画.为此我写下了一段代码.
代码1:
for (int j=0;j<10;j++){
int randomNum = random.nextInt(6);
System.out.println("Random Value " + randomNum);
dice.setImageResource(images[randomNum]);
}
Run Code Online (Sandbox Code Playgroud)
输出:
没有视觉效果.imageView保持不变,并在循环最后一次迭代时突然改变.我认为这是因为循环执行速度非常快.然后我做了以下.
代码2:
for (int j=0;j<10;j++){
int randomNum = random.nextInt(6);
System.out.println("Random Value " + randomNum);
dice.setImageResource(images[randomNum]);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
再一次没有视觉效果.imageView保持不变,并在循环最后一次迭代时突然改变.然后我做了以下.
代码3:
final Handler localHandler = new Handler();
Runnable runnableObject = new Runnable() {
public void run() {
final ImageView dice = (ImageView) findViewById(R.id.imageViewrollingdiceOne);
int randomNum = random.nextInt(6);
System.out.println("Random Value" + randomNum);
dice.setImageResource(images[randomNum]);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
for (int j=0;j<10;j++){
localHandler.postDelayed(runnableObject, 1000);
}
Run Code Online (Sandbox Code Playgroud)
再一次没有视觉效果.imageView保持不变,并在循环最后一次迭代时突然改变.在所有三种情况下,logcat都没有任何错误.
我发现线程也不能解决问题.
首先,在Android中已经有一个动画集可以帮助你在它被称为FrameAnimation之后获得你所拥有的东西,下面是一个如何使用它的例子:
你的第一,第二和第三个代码在主线程中运行,你不应该在主线程中使用sleep!
如果您仍想手动设置图像资源,可以使用以下代码:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
int randomNum = random.nextInt(6);
dice.setImageResource(images[randomNum]);
handler.postDelayed(this, 500);
}
}, 500);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9302 次 |
| 最近记录: |