How do i open fragment from fragment (kotlin)

Viewed 21692

I'm finding a way to move fragment to fragment by using ClickListener; but I have no idea how to move fragment to fragment.

I want move like this :

A fragment have 4 cardview

click 1 cardview : move to fragment B
click 2 cardview : move to fragment C
click 3 cardview : move to fragment D
click 4 cardview : move to fragment F

I have done fragment move to activity by using code below

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        power655Card.setOnClickListener {
            val intent = Intent (getActivity(), Power655Activity::class.java)
            getActivity()?.startActivity(intent)
        }
3 Answers

In Kotlin, if you want to load various fragment inside activity, you can make one function which you call wherever required to load the fragment.

private fun loadFragment(fragment: Fragment){
    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fl_main, fragment)
    transaction.disallowAddToBackStack()
    transaction.commit()
}

And if you want to load fragment from a fragment,

    val transaction = activity.supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fl_main, SecondFragment())
    transaction.disallowAddToBackStack()
    transaction.commit()

In the above code spinnet, SecondFragment() is the instance of the fragment which you wish to load. So we can also pass the instance of the fragment as shown above.

You can use requireActivity().supportFragmentManager.beginTransaction() to make the fragments transactions you need to.

You can change fragment putting this in you listener:

val fragmentB = FragmentB()
activity.getSupportFragmentManager().beginTransaction()
             .replace(R.id.layout_container, fragmentB, "fragmnetId")
             .commit();

R.id.layout_container is the fragment container in you activity xml

fragmentId is the id of the fragment so you can refer to it later.

Related