Junfei Wang
Junfei Wang

Reputation: 578

dynamically change bitmap in imageView, android

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

Answers (3)

Dmytro Danylyk
Dmytro Danylyk

Reputation: 19798

  1. You should have exception, as you can work with view's only in UI Thread. You should call post method on your view if you want to make changes with it.
  2. Actually it is changed so fast that you see only last item.

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

dan
dan

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

DeeV
DeeV

Reputation: 36035

  1. 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.

  2. 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.

  3. 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

Related Questions