Home > Software design >  How to start another activity in function? Kotlin
How to start another activity in function? Kotlin

Time:12-23

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val navigate = Intent(this,Activity2::class.java)
            startActivity(navigate)
        }
    }
}

fun switchActivity(){
    val navigate = Intent(this,Activity2::class.java)
    startActivity(navigate)
}

I want to start an activity from a function and not from the main activity.. I can start an activity from main class but in function, the code doesnt work.. Please help.. I'm new to kotlin android programming..

CodePudding user response:

Just use it

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        switchActivity()
    }
}

fun switchActivity(){
    val navigate = Intent(this@MainActivity, Activity2::class.java)
    startActivity(navigate)
}

CodePudding user response:

If your function is declared at the top level, without a reference to this, you'd need to pass an instance of Activity to your function:

fun switchActivity(activity: Activity) {
    val navigate = Intent(activity, Activity2::class.java)
    startActivity(navigate)
}

CodePudding user response:

You can also try like this

    class MainActivity : AppCompatActivity() {
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        nextActivity(this, MainActivity2())
    }


    private fun nextActivity(context: Context, activity: Activity) {
        startActivity(Intent(context, activity::class.java))
    }
}

CodePudding user response:

Actually i don't get your question clearly. But i'll try to answer your question based on my understanding of yours.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            switchActivity()
            // if you want to pass the class through the paramater,
            // can try this
            // TODO: Another Way
            // switchActivityCustom(Activity2::class.java)
        }
    }

    fun switchActivity(){
        val navigate = Intent(this, Activity2::class.java)
        startActivity(navigate)
    }

    // TODO: Another Function
    // fun switchActivityCustom(destination: Class<*>,){
    //    val navigate = Intent(this, destination)
    //    startActivity(navigate)
    // }
}

And the last one is, put your function inside the class (in this case: MainActivity Class)

  • Related