Dan Methad Dan Methad - 1 month ago 14
Android Question

Add a View Programmatically With Delay

I'm trying to add 4 X

ImageView
with 1 sec
delay
between each one,
my code is:

final LinearLayout ll = (LinearLayout) findViewById(R.id.container);
for (int j=0;j<4;j++){
final ImageView newIMG = new ImageView(this);
newIMG.setLayoutParams(
new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT,
1.0f));
newIMG.setImageResource(R.drawable.new_image);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
ll.addView(newIMG);
}
}, 1000);
}


But what i get is - it waits for a sec and then
display
all the
ImageViews
at once...
(and i want them to show one after another)

Answer

Try :

final LinearLayout ll = (LinearLayout) findViewById(R.id.container);
for (int j=0;j<4;j++){
    final ImageView newIMG = new ImageView(this);
    newIMG.setLayoutParams(
                    new LayoutParams(LayoutParams.WRAP_CONTENT, 
                                     LayoutParams.MATCH_PARENT, 
                                     1.0f));
    newIMG.setImageResource(R.drawable.new_image);
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
         public void run() { 
                ll.addView(newIMG);
         } 
    }, j*1000 + 1000); 
}