-1

Have a fragment in which I display the recyclerView list. When I click on a list item in MainActivity I call the method:

fun FragmentActivity?.replaceFragment(fragment: Fragment): Boolean {
    if (this == null) return false
    try {
        supportFragmentManager?.beginTransaction()?.replace(
            R.id.container, fragment,
            fragment.createTagName()
        )?.commit()
    } catch (ignored: IllegalStateException) {
        return false
    }
    return true
}

After this I press the system back button and I have a duplicate list.

Also i have in my MainActivity next fun:

 override fun onBackPressed() {
        val onBackPressListener = currentFragmentInContainer() as? OnBackPressListener
        if (onBackPressListener?.onBackPress() != true) {
            super.onBackPressed()
        }
    }
Morozov
  • 4,968
  • 6
  • 39
  • 70

1 Answers1

1

The issue is you have not added the current fragment to the back stack. In order to get to the starting point, you have to mark the fragment. addToBackStack(tag:String) will help you to do that.

Code:

fun FragmentActivity?.replaceFragment(fragment: Fragment): Boolean {
    if (this == null) return false
    try {
        supportFragmentManager?.beginTransaction()?.replace(
            R.id.container, fragment,
            fragment.createTagName()
        ).addToBackStack(fragment.createTagName())?.commit()
    } catch (ignored: IllegalStateException) {
        return false
    }
    return true
}

Here is the documentation about the method : addToBackStack

Jaymin
  • 2,879
  • 3
  • 19
  • 35
  • Problem is not resolved( Maybe here the problem is also in the data but I can't say for sure yet – Morozov Aug 21 '19 at 13:12