Kotlin: open new Activity inside of a Fragment

后端 未结 13 2260
醉话见心
醉话见心 2020-12-05 16:32

How can I open a new Activity inside of a fragment when using a button?

I tried this

override fun onViewCreated(view: View, savedInstanceState: Bundle?         


        
13条回答
  •  天涯浪人
    2020-12-05 17:18

    Your code is almost done, you just need to pass the fragment instance as the first parameter of Intent replace YourFragmentName with your fragment name after the @, bellow:

    val intent = Intent (this@YourFragmentName.context, Main::class.java)
    startActivity(intent)
    

    Look at this sample bellow:

    class MyFragment: Fragment(){
    
        override fun onActivityCreated(savedInstanceState: Bundle?) {
            super.onActivityCreated(savedInstanceState)
    
            val intent = Intent (this@MyFragment.context, YOUR_NEXT_ACTIVITY_CLASS::class.java)
            startActivity(intent)
        }
    }
    

提交回复
热议问题