Kotlin: open new Activity inside of a Fragment

后端 未结 13 2129
醉话见心
醉话见心 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:08

    Here is the solution I found while trying to get something similar to work.

    view.findViewById<Button>(R.id.button_second).setOnClickListener {
      val i = Intent(activity, ClassNameOfActivityIWantToGoTo::class.java)
      activity?.startActivity(i)
    }
    
    0 讨论(0)
  • 2020-12-05 17:11

    For me i just did this and it worked

    val intent = Intent(AppName.applicationContext(), YourAppName::class.java)
    activity?.startActivity(intent)
    

    You can add this code into your fragment

    AppName
    

    This is the Application name which holds global companion object like context

    0 讨论(0)
  • 2020-12-05 17:15

    FirebaseAuth.getInstance().signOut() before the intent.

    0 讨论(0)
  • 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)
        }
    }
    
    0 讨论(0)
  • 2020-12-05 17:18

    Also an option (for kotlin). In onCreateView set onClickListener for a button:

    button.setOnClickListener {
        requireActivity().run {
            startActivity(Intent(this, MainActivity::class.java))
            finish() // If activity no more needed in back stack
        }
    }
    
    0 讨论(0)
  • 2020-12-05 17:19

    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)
    }
    
    0 讨论(0)
提交回复
热议问题