Search code examples
androidandroid-fragmentsandroid-fragmentactivityonbackpressed

Problem with navigating fragments when i press on back


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()
        }
    }

Solution

  • 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