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?
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)
}
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
FirebaseAuth.getInstance().signOut() before the intent.
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)
}
}
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
}
}
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)
}