3

Kotlin in Android Studio here.

I'm trying to get an imageView to fade into the main view, wait a few seconds, then fade out. For the life of me I can't find any documentation on pausing or waiting anywhere. It's driving me nuts.

How do I tell my function to just chill out and wait for 3 seconds, then continue executing the rest of the function's code?

Ideally, I would have it between:

imageView.startAnimation(animIn)
imageView.startAnimation(animOut)

Any help is very appreciated!

Zoo

ZoologyKT
  • 45
  • 1
  • 7

5 Answers5

4

You can use Handler,

Handler().postDelayed(Runnable { 
    //anything you want to start after 3s
}, 3000)
flx_h
  • 101
  • 3
  • I get an error: Cannot access it is protected/*protected and package*/ in 'Handler' Sorry, I'm a noob. :L – ZoologyKT Jun 10 '19 at 03:53
  • 1
    I think you use a wrong Handler class, make sure there is import android.os.Handler on the top, Maybe you use java.util.logging.Handler – flx_h Jun 10 '19 at 04:00
3

Since this is specific to Kotlin and not just Android. Why not use coroutines?

GlobalScope.launch {
    imageView.startAnimation(animIn)
    delay(3_000L)
    imageView.startAnimation(animOut)
}

This is a naive example, launching on the GlobalScope, and some of the overhead of setting up/getting your head around coroutines might mean it doesn't suit your use case. But if you're already using coroutines in your app, or expecting to in the future then this code is quite clear in it's intent.

Mike Simpson
  • 426
  • 4
  • 8
0

import the android.os.Handler and try the following:

Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                // yourAnimationMethod();
            }
        }, 1000); // 1000 milliseconds

If you are looking for a one-liner, you can try:

(new Handler()).postDelayed(this::yourAnimationMethod, 1000); // 1000 milliseconds
jxing8
  • 11
  • 3
  • If you are using Kotlin, you may need to convert Java to Kotlin for this to work. Please refer to https://androidride.com/convert-java-class-to-kotlin-android-studio/ – jxing8 Jun 10 '19 at 04:01
0

you can use :

Timer("SettingUp", false).schedule(timeyouwant_in_milleseconds) { 
   imageView.startAnimation(animOut)
}
ismail alaoui
  • 5,748
  • 2
  • 21
  • 38
0

Stopping the main thread for a few seconds is not a good idea. You can use handler instead. The code below will create a task which will be executed after a delay. Anything put inside the run() method will be executed after a delay.

new Handler().postDelayed(new Runnable()
{
   @Override
   public void run()
   {
     imageView.startAnimation(animOut)
   }
}, 3000);