How to Add a Fragment the Kotlin way

Bob
Bob
Aug 17, 2017 · 4 min read
Image for post
Image for post
Image Source: Kotlin on Android
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(frameId, fragment);
transaction.commit();
public static void addFragmentToActivity(FragmentManager manager, Fragment fragment, int frameId) {

FragmentTransaction transaction = manager.beginTransaction();
transaction.add(frameId, fragment);
transaction.commit();

}
ActivityUtil.addFragmentToActivity(
getSupportFragmentManager(), fragment, R.id.frag_container);
inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> Unit) {
val fragmentTransaction = beginTransaction()
fragmentTransaction.func()
fragmentTransaction.commit()
}
supportFragmentManager.inTransaction {
add(R.id.frameLayoutContent, fragment)
}
supportFragmentManager.inTransaction {
remove(fragmentA)
add(R.id.frameLayoutContent, fragmentB)
}
inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) {
beginTransaction().func().commit()
}
fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int){
supportFragmentManager.inTransaction { add(frameId, fragment) }
}


fun AppCompatActivity.replaceFragment(fragment: Fragment, frameId: Int) {
supportFragmentManager.inTransaction{replace(frameId, fragment)}
}
addFragment(fragment, R.id.fragment_container)

replaceFragment(fragment, R.id.fragment_container)

Thoughts Overflow

My thoughts on Coding, Android, UI/UX, Life, Love

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store