Search code examples
javaandroidanimationrunnablepostdelayed

delay animation before restarting the activity


I've a GifImageButton view. I want to start its animation and then restart the activity.

The problem is that I want the animation to last 3 seconds before restarting the activity.

How can I do it?

this is my code:

myGifImageButton.setImageResource(R.drawable.animation);
Intent intent = getIntent();
finish();
if (intent != null) {
    startActivity(intent);
}

As I read, the better way is to use a runnable so I tried this but I didn't succeed it:

// start the animation
myGifImageButton.setImageResource(R.drawable.animation);

// delay the animation
mHandler = new Handler();
final Runnable r = new Runnable() {
    void run() {
        handler.postDelayed(this, 3000);
    }
};
handler.postDelayed(r, 3000);

// restart the activity
Intent intent = getIntent();
finish();
if (intent != null) {
    startActivity(intent);
}

so how can I delay the animation before restarting the activity?


Solution

  • Yor runnable is incorrect - you are continously reposting the same runnable which does nothing.

    Instead try something like this:

    // start the animation
    myGifImageButton.setImageResource(R.drawable.animation);
    
    // delay the animation
    mHandler = new Handler();
    final Runnable r = new Runnable() {
        void run() {
           // restart the activity
           Intent intent = getIntent();
           finish();
           if (intent != null) {
               startActivity(intent);
           }
        }
    };
    handler.postDelayed(r, 3000);