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?
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)
}
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
val intent = Intent(activity, AttachmentActivity::class.java)
activity!!.startActivity(intent)
activity!!.finish()
You can do smth like this in kotlin
YourButton.setOnClickListener{
requireActivity().run{
startActivity(Intent(this, NeededActivity::class.java))
finish()
}
}
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)
}
}
I believe it would be something like
activity?.let { callingActivity -> startActivity(Intent(callingActivity, Main::class.java)) }
You must use the calling activities context