Kotlin: open new Activity inside of a Fragment

Because Fragment is NOT of Context type, you'll need to call the parent Activity:

 val intent = Intent (getActivity(), Main::class.java)
 getActivity().startActivity(intent)

or maybe something like

activity?.let{
    val intent = Intent (it, Main::class.java)
    it.startActivity(intent)
}

You can do smth like this in kotlin

YourButton.setOnClickListener{
            requireActivity().run{
                startActivity(Intent(this, NeededActivity::class.java))
                finish()
            }
        }

val intent = Intent (getActivity(), NextActivity::class.java)
getActivity()?.startActivity(intent)

This will do the job.

getActivity() as it's casted from a Fragment and getActivity()? to avoid NPE

Hope it helps :)


If you only use activity returns just an Activity instance. This can be any activity that embeds your fragment so in some cases you can get FragmentActivity instead your parent activity. Use this to make sure you are getting the correct one:

(activity as? YourParentActivity)?.let{
    val intent = Intent (it, Main::class.java)
    it.startActivity(intent)
}