Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: open new Activity inside of a Fragment

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?) {
    super.onViewCreated(view, savedInstanceState)

    LogOut_btn.setOnClickListener {
        //FirebaseAuth.getInstance().signOut()
        val intent = Intent (this, Main::class.java)
        startActivity(intent)            
    }
}

val intent = Intent doesn't seem to work in a fragment.

Any idea how I can start a new activity inside a fragment?

like image 647
L. Busekrus Avatar asked Nov 17 '18 21:11

L. Busekrus


People also ask

Can you start a new activity from a fragment?

If you want to start a new instance of mFragmentFavorite , you can do so via an Intent . Intent intent = new Intent(this, mFragmentFavorite. class); startActivity(intent); If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent .

How do you call an activity inside a fragment?

Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.

Can a fragment contain an activity?

A fragment represents a modular portion of the user interface within an activity. A fragment has its own lifecycle, receives its own input events, and you can add or remove fragments while the containing activity is running.


1 Answers

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)
}
like image 124
dasfima Avatar answered Sep 19 '22 20:09

dasfima