Search code examples
androidkotlinsplash-screen

how i code the SplashScreenActivity.kt cuz mine doesn't work


i want to add a splash screen to my app so i created an activity with a name of SplashScreen and i add this code to the SplashScreenActivity.kt but the android studio doesnt reconize java in
val i = Intent(this@MainActivity, MainActivity::class.java) and it shown as red Note that i use kotlin

package com.example.textnav

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity


class SplashScreen : AppCompatActivity() {
    private val SPLASH_TIME_OUT = 3000L

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


                Handler().postDelayed(
                    {
                        val i = Intent(this@MainActivity, MainActivity::class.java)
                        
                        startActivity(i)
                        finish()
                    }, SPLASH_TIME_OUT
                )
            }
        }

the pic

the mainactivity.kt

package com.example.textnav

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Solution

  • Handler().postDelayed(
        {
            val i = Intent(this,MainActivity::class.java)
            startActivity(i)
            finish()
        }, 
        SPLASH_TIME_OUT
    )
    

    this refers to the { } lambda that you are inside (which is a Runnable).

    Try:

    val i = Intent(this@SplashScreen, MainActivity::class.java)

    to get the this from an outer scope (your activity).

    The Intent constructor you called expects a Context as its first parameter. Your this is of the type Runnable. With this@SplashScreen you are using the type Activity (which is a Context).