Search code examples
javaandroidxmlkotlin

How to Convert java to kotlin in handler


how to Convert java to kotlin in handler

new Handler().postDelayed(new Runnable(){
    @Override
    public void run() {
        /* Create an Intent that will start the Menu-Activity. */
        Intent mainIntent = new Intent(Splash.this,Menu.class);
        Splash.this.startActivity(mainIntent);
        Splash.this.finish();
    }
}, 3000);

Solution

  • Java converted to Kotlin:

    Handler(Looper.getMainLooper()).postDelayed({
        val mainIntent = Intent(this, Menu::class.java)
        startActivity(mainIntent)
        finish()
    }, 3000)
    

    If you are using the androidx-core-ktx package, there is an extension function which reorders the arguments to be more suitable for Kotlin:

    Handler(Looper.getMainLooper()).postDelayed(1000) {
        // Do something
    }