0

Here's my attempt:

private inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) {
        beginTransaction().func().addToBackStack(null).commit()
    }

private fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int){
        supportFragmentManager.inTransaction { add(frameId, fragment) }
    }

private fun AppCompatActivity.showFragment(fragment: Fragment) {
        supportFragmentManager.inTransaction{show(fragment)}
    }

private fun showFragmentView(fragment: Fragment){

        // Hide the current Fragment
        if (supportFragmentManager.fragments.isNotEmpty()) {
            val currentFragment = supportFragmentManager.fragments.last()
            if (currentFragment != null) {
                supportFragmentManager
                        .beginTransaction()
                        .hide(currentFragment)
                        .commit()
            }
        }

        // Add or Show
        if (!fragment.isAdded) {
            addFragment(fragment, sendFragFrame.id)
        } else {
            showFragment(fragment)
        }
    }

It properly adds the fragment to the frame, but when I attempt to hide it nothing happens, it's stays visible and the second fragment cannot be seen. Can someone explain why this is happening?

szaske
  • 1,887
  • 22
  • 32

2 Answers2

1

It is not good practice (and most likely won't work) to access fragments in this way.

  if (supportFragmentManager.fragments.isNotEmpty()) {
            val currentFragment = supportFragmentManager.fragments.last()
            if (currentFragment != null) {
                supportFragmentManager
                        .beginTransaction()
                        .hide(currentFragment)
                        .commit()

You should add fragments with a tag and get the fragment by tag when you want to remove it and then do your transaction.

See the comments on this for more: How do I get the currently displayed fragment?

Richard Dapice
  • 838
  • 5
  • 10
0

Well embarrassingly my problem was that I had inadvertently swap my layout in Fragment2 with the layout for Fragment1...so it WAS working, but because they shared a layout you couldn't see it visually. I'd delete this post if I could, but I'll leave it here as tribute to my shame as a developer.

szaske
  • 1,887
  • 22
  • 32