Search code examples
androidkotlinandroid-activitythread-sleep

How to create a splash activity with kotlin in android?


I am trying to create a splash activity in my android app. On the beginning of the app, I want the app to stay in splash activity for 2 seconds and go to main activty. The splash activity only contains the app icon. Here's the xml code:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto"
         xmlns:tools="http://schemas.android.com/tools"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         tools:context=".views.SplashActivity">


        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_centerInParent="true"
            android:layout_marginStart="172dp"
            android:layout_marginTop="330dp"
            app:srcCompat="@mipmap/ic_launcher_round" />
    </RelativeLayout>

And this is the SplshActivity.kt :

class SplashActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        goToMain()
    }

    private fun goToMain() {
         Thread.sleep(2000)
        val i = Intent(this@SplashActivity, MainActivity::class.java)
        finish()
        startActivity(i)
    }
}

Splash Activity is going to Main Activity after 2 seconds correctly. But, the problem is that when i run the app, splash activity is blank. Imageview is missing from the activity. I tried putting the goToMain() in onStart() and onResume(). Still no luck. What am I doing wrong?


Solution

  • Here is your answer in kotlin :

    Handler().postDelayed({
                val mIntent = Intent(this@SplashActivity, MainActivity::class.java)
                startActivity(mIntent)
                finish()
            }, 2000)