Kotlin: open new Activity inside of a Fragment

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

    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 use you are getting the correct one:

    (activity as YourParentActivity?)?.let{
        val intent = Intent (it, Main::class.java)
        it.startActivity(intent)
    }
    
    0 讨论(0)
  • 2020-12-05 17:20
    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

    0 讨论(0)
  • 2020-12-05 17:22
    val  intent = Intent(activity, AttachmentActivity::class.java)
                activity!!.startActivity(intent)
                 activity!!.finish()
    
    0 讨论(0)
  • 2020-12-05 17:23

    You can do smth like this in kotlin

    YourButton.setOnClickListener{
                requireActivity().run{
                    startActivity(Intent(this, NeededActivity::class.java))
                    finish()
                }
            }
    
    0 讨论(0)
  • 2020-12-05 17:23

    Try getting the context from the fragment instead

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      super.onViewCreated(view, savedInstanceState)
    
      LogOut_btn.setOnClickListener {
        //FirebaseAuth.getInstance().signOut()
         val intent = Intent (view.context, Main::class.java)
        startActivity(intent)
      }
    }
    
    0 讨论(0)
  • 2020-12-05 17:26

    I believe it would be something like

    activity?.let { callingActivity -> startActivity(Intent(callingActivity, Main::class.java)) }
    

    You must use the calling activities context

    0 讨论(0)
提交回复
热议问题