Android - Loading images with a delay

♀尐吖头ヾ 提交于 2019-12-11 02:42:46

问题


I'm trying to fake some kind of progress bar. I have X images and want an ImageView to show them with a certain delay.

I've tried to do something like this:

for(i=2;i<X;i++) 
{
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {  

              @Override
              public void run() {

               drawable = getResources().getDrawable(getResources()
                                .getIdentifier("img_"+i, "drawable", getPackageName()));

               imgPayment.setImageDrawable(drawable);
               }}, DELAY);                  
}

But the for loop doesn't wait for the run() to end. I just see the first and last image. I tried a few other things but couldn't get the desired results.


回答1:


Why are you not using an Animation Drawable? It seems that you're not loading the images dynamically.

 <animation-list android:id="@+id/selected" android:oneshot="false">
    <item android:drawable="@drawable/wheel0" android:duration="50" />
    <item android:drawable="@drawable/wheel1" android:duration="50" />
    ...
 </animation-list>

Did I miss something?

Link to the Docs

Link to sample

As the sample docs state:

It's important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the onWindowFocusChanged() method in your Activity, which will get called when Android brings your window into focus.




回答2:


What about using Thread.sleep()? If you set sleeping interval of each image in an incremental manner, they will be displayed as if they are ordered.

for (i = 1; i < X; i++) 
{
    //Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() 
        {
            Thread.sleep(i * 1000); // REMARK HERE!
            drawable = getResources().getDrawable(getResources().getIdentifier
                                  ("img_" + i, "drawable", getPackageName()));
            imgPayment.setImageDrawable(drawable);
        }
    });
}

However, to be able to use the variable i as in the code above, declare it as a global static variable.

static int i = 0;



回答3:


I would recommend using an ASyncTask and then update your drawable from there or using a callback.



来源:https://stackoverflow.com/questions/12977039/android-loading-images-with-a-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!