Java 在循环中更改图像-Android
我想知道为什么我仍然不能想出一个方法来做这件事。虽然看起来很简单,但我花了一整天的时间来做这件事。但我不能这么做 我有一套骰子图像。1.png,2.png,。。。。和6.png。 我的布局中有一个ImageView。就是Java 在循环中更改图像-Android,java,android,for-loop,thread-sleep,Java,Android,For Loop,Thread Sleep,我想知道为什么我仍然不能想出一个方法来做这件事。虽然看起来很简单,但我花了一整天的时间来做这件事。但我不能这么做 我有一套骰子图像。1.png,2.png,。。。。和6.png。 我的布局中有一个ImageView。就是 ImageView dice = (ImageView) findViewById(R.id.imageViewrollingdiceOne); 在这里,我想快速更改此imageView,以查看使用上述6幅图像的某种视觉/动画。为此,我编写了以下代码 代码1: for (in
ImageView dice = (ImageView) findViewById(R.id.imageViewrollingdiceOne);
在这里,我想快速更改此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]);
}
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();
}
}
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);
}
for(int j=0;j您可能看不到更改的原因是,对主UI线程的最终回调发生在您的线程完成其执行之后,您只看到最终结果。现在,这是我(可能很差)的理解,更精通这方面的人可能会纠正我
也就是说您可能应该使用AnimationDrawable
对象:
ImageView sImage = (ImageView)findViewById(R.id.imageViewrollingdiceOne);
AnimationDrawable anim = new AnimationDrawable();
for (int j=0;j<6;j++) {
anim.addFrame(new BitmapDrawable(images[j], 200);
}
sImage.setBackgroundDrawable(anim);
anim.setOneShot(false);
anim.start();
ImageView sImage=(ImageView)findViewById(R.id.imageViewrollingdiceOne);
AnimationDrawable anim=新的AnimationDrawable();
对于(int j=0;j首先,android中已经有一个动画集,它可以帮助您在被称为后实现自己的身份,下面是一个如何使用它的示例:
您的第一、第二和第三个代码正在主线程中运行,您不应该在主线程中使用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);
当您使用项目列表并根据时间间隔逐个更改时,这很有用。最初i
值应为0,列表大小取决于
final Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
if(i<4) {
galleryImg.setImageResource(myImageList[i]);
i++;
} else {
i=0;
}
handler.postDelayed(this, 10000);
}
}, 500);
final Handler=new Handler();
handler.postDelayed(新的Runnable(){
公开募捐{
if(我非常感谢你,Mr.Me.runnable代码工作得很好。我之前也使用过这个,但问题是我没有调用handler.postDelayed(这个,500);
方法。非常感谢。使用这个解决方案,第一个动画周期的第一帧在200ms后出现。有什么办法解决这个问题吗?