Any code improvement in adding/replacing fragment

Viewed 3787

I have started to study Kotlin and do not know all the functionality of the language.

The function is used to show the fragment in the FrameLayout. The logic is so that the first time it should always add() the fragment and next times it will replace(). Also in some cases I need to use addToBackStack() and also in the same situations to disable the left-side menu.

fun showFragment(fragment : Fragment,
                 isReplace: Boolean = true,
                 backStackTag: String? = null,
                 isEnabled: Boolean = true)
{
    /* Defining fragment transaction */
    val fragmentTransaction = supportFragmentManager
            .beginTransaction()

    /* Select if to replace or add a fragment */
    if(isReplace)
        fragmentTransaction.replace(R.id.frameLayoutContent, fragment, backStackTag)
    else
        fragmentTransaction.add(R.id.frameLayoutContent, fragment)

    /* Select if to add to back stack */
    if(backStackTag != null)
        fragmentTransaction.addToBackStack(fragment.javaClass.name)

    fragmentTransaction.commit()
    enableDrawer(isEnabled)
}

Question: Are there some possible improvements of the function code related to the specifications of Kotlin language to make code cleaner as for now the function looks as a mass.

5 Answers

You can create an extension function like this:

  1. Import android.support.v4.app.FragmentManager and android.support.v4.app.FragmentTransaction if you wish to make your app compatible with devices running system versions as low as Android 1.6 using supportFragmentManager(which uses the support library) instead of fragmentManager.

  2. Define the following function on the top level, i.e. directly under the package:

    inline fun FragmentManager.inTransaction(func: FragmentTransaction.() Unit) {
        val fragmentTransaction = beginTransaction()
        fragmentTransaction.func()
        fragmentTransaction.commit() 
    }
    
  3. Call the function from any activity:

    supportFragmentManager.inTransaction {
        add(R.id.frameLayoutContent, fragment)
    }
    

You can use below code for replace:

fun Fragment.moveAnotherFragment(fragment: Fragment,addToBackStack: Boolean = true, func : Bundle?. () -> Unit = {}) {

fragment.enterTransition =
    activity?.supportFragmentManager?.beginTransaction()?.apply {
        replace(
            R.id.frame, fragment.apply {
                enterTransition = Slide(Gravity.END)
                exitTransition = Slide(Gravity.START)
                arguments.apply(func)
            }
        )
        if (addToBackStack) addToBackStack(null)
        commit()
    }

}

Related