简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM