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.
Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container. transaction. commit();
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.
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()
}
The other answers will work but still we can improve a lot by using extension functions in Kotlin.
Add an extension function to the FragmentManager class like below,
inline fun FragmentManager.doTransaction(func: FragmentTransaction.() ->
FragmentTransaction) {
beginTransaction().func().commit()
}
then create an extension function to the AppCompatActivity class,
fun AppCompatActivity.addFragment(frameId: Int, fragment: Fragment){
supportFragmentManager.doTransaction { add(frameId, fragment) }
}
fun AppCompatActivity.replaceFragment(frameId: Int, fragment: Fragment) {
supportFragmentManager.doTransaction{replace(frameId, fragment)}
}
fun AppCompatActivity.removeFragment(fragment: Fragment) {
supportFragmentManager.doTransaction{remove(fragment)}
}
Now, to add and remove fragments from any activity, you just need to call like this,
addFragment(R.id.fragment_container, fragment)
replaceFragment(R.id.fragment_container, fragment)
please refer the below link for more info,
https://medium.com/thoughts-overflow/how-to-add-a-fragment-in-kotlin-way-73203c5a450b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With