Reputation: 578
All,
I have a problem related to imageView, android.
I have array which contains of 10 bitmap objects, called bm
.
I have a imageView, called im
.
Now I wanna show the bitmaps in the array in im one by one, so I did the following:
new Thread(new Runnable() {
public void run() {
for(int j=0;j<10;j++){
im.setImageBitmap(bm[j]);
}
}
}).start();
But the result only shows the last bitmap in the array.
Can someone tell me what to do with this issue?
Millions of thanks!
Upvotes: 2
Views: 5572
Reputation: 19798
Here is correct code:
new Thread(new Runnable() {
public void run()
{
for (int j = 0; j < 10; j++)
{
final int index = j;
im.postDelayed(new Runnable() {
@Override
public void run()
{
im.setImageBitmap(bm[index]);
}
}, j * 1000); // delay j seconds
}
}
}).start();
Upvotes: 1
Reputation: 13272
You need insert a sleep
call after setting a new image so that your eyes will have the chance to see the images :). Something like:
im.setImageBitmap(bm[j]);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Should keep the image for five seconds before advancing to the next one.
Like others have suggested, you will need use postDelayed
to properly notify the UI that you are setting a bitmap.
Upvotes: 1
Reputation: 36035
Don't ever change a UI element in a thread. Most of the time this results in an exception. I don't know why it didn't here.
You're blasting through all ten images in a mere milliseconds. That's why the last one is the only one you see. You need to slow it down.
The easiest way would be the Handler/Runnable implementation like so:
im.post(new Runnable() {
int j = 0;
@Override
public void run() {
im.setImageBitmap(bm[j]);
if(j++ < 10){
im.postDelayed(this, 1000);
}
}
});
Upvotes: 1