aleksandrbel aleksandrbel - 5 months ago 20
Android Question

Any code improvement in adding/replacing fragment

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.

Answer Source

I like to use with and let when I have some code related to using a lot some variable and null checks

So I'd do something like this:

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

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

        /* Select if to add to back stack */
        backStackTag?.let { addToBackStack(it) }

        commit()
    }
    enableDrawer(isEnabled)
}