问题
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