Search code examples
androidtimerimageviewdelay

How to set an image with a delay


I have an "Activity" with three images. When one image is clicked, all the images are to switch to another picture. Is there a way to make the switches such that there is a 2 second delay before the images actually change (i.e. a 2 second delay in every 'for loop' below)? I am trying to do this with a timer but it does not actually to the delay when I run my program:

protected void onCreate(Bundle savedInstanceState) {
image1.setOnClickListener(this);

@Override
public void onClick(View arg0) 
{
do_switches();
}

private void do_switches() 
{
//loop through all images and change them
for(int j=1 ;j<=3; j++)
{           


 final int curr2=current;
 final Handler handler = new Handler(); 
 Timer t = new Timer(); 
 t.schedule(new TimerTask() { 
       public void run() { 
        handler.post(new Runnable() { 
               public void run() { 

        switch(curr2){

        case 1:

            image1.setImageResource(ImageArray[1]);
                    break;

        case 2:

            image2.setImageResource(ImageArray[2]);
                             break;

        case 3:
            image3.setImageResource(ImageArray[3]);
                        break;

        }
            } 
        }); 
    } 
 }, 2000); 
}

}

I have also tried using just SystemClock.sleep(2000) instead of the timer but I that didnt work either.I also tried setting up a Thread with a try/catch with no luck or maybe I didn't implement it properly. Is there a way to put this delay on every iteration of my for loop? Thanks


Solution

  • Not one of best option, but still you can try CountDownTimer.

    http://developer.android.com/reference/android/os/CountDownTimer.html