Search code examples
androidandroid-fragmentskotlinfragment

How to change Fragment Kotlin


I'm starting in Kotling and I don't know how to change between fragments, I have tried this code:

val manager = supportFragmentManager
    val transaction = manager.beginTransaction()
    transaction.add(R.layout.fragment_information.toInt(), ComplainFragment())
    transaction.commit()

R.layout.fragment_information.toInt()

But i have an error with this parameter because it doesn't find the fragment Id.


Solution

  • I usually use replace to change between fragments. Also change R.layout.fragment_information to R.id.fragment_layout_id only, so no need toInt()

    transaction.replace(R.id.fragment_layout_id, fragment)
    

    Here is my suggestion.

        var fragment: Fragment? = null
    
                when (itemId) {
                            R.id.fragment_information -> {
                                fragment = ComplainFragment()
                            }
                }
    
                if (fragment != null) {
                        val transaction = supportFragmentManager.beginTransaction()
                        transaction.replace(R.id.fragment_layout_id, fragment)
                        transaction.commit()
                }